<!DOCTYPE html>
<html class="client-nojs vector-feature-night-mode-disabled vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-sticky-header-enabled" lang="en" dir="ltr"><head>
<meta charset="UTF-8">
<title>Scope (computer science)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="https://en.wikipedia.org/wiki/Scope_(computer_science)"> <link href="./mw/ext.cite.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/ext.pygments.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.icons.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.search.codex.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/user.styles.css" rel="stylesheet" type="text/css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" type="text/css" href="./mw/site.styles.css">
<link rel="stylesheet" type="text/css" href="./mw/noscript.css">
<link rel="stylesheet" type="text/css" href="./footer.css">
<link rel="stylesheet" type="text/css" href="./vector-2022.css">
</head>
<body class="skin--responsive skin-vector skin-vector-search-vue mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Scope_computer_science rootpage-Scope_computer_science skin-vector-2022 action-view">
<div class="mw-page-container">
<div class="mw-page-container-inner">
<div class="mw-content-container">
<main id="content" class="mw-body">
<header class="mw-body-header vector-page-titlebar">
<h1 id="firstHeading" class="firstHeading mw-first-heading">
<span id="openzim-page-title" class="mw-page-title-main"><span class="mw-page-title-main">Scope (computer science)</span></span>
</h1>
</header>
<a id="top"></a>
<div id="bodyContent" class="vector-body ve-init-mw-desktopArticleTarget-targetContainer" aria-labelledby="firstHeading" data-mw-ve-target-container="">
<div id="mw-content-text" class="mw-body-content mw-content-ltr" lang="en" dir="ltr"><div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr">
<style data-mw-deduplicate="TemplateStyles:r1251242444">
/* start https://en.wikipedia.org/ */
.mw-parser-output .ambox{border:1px solid #a2a9b1;border-left:10px solid #36c;background-color:#fbfbfb;box-sizing:border-box}.mw-parser-output .ambox+link+.ambox,.mw-parser-output .ambox+link+style+.ambox,.mw-parser-output .ambox+link+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+style+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+link+.ambox{margin-top:-1px}html body.mediawiki .mw-parser-output .ambox.mbox-small-left{margin:4px 1em 4px 0;overflow:hidden;width:238px;border-collapse:collapse;font-size:88%;line-height:1.25em}.mw-parser-output .ambox-speedy{border-left:10px solid #b32424;background-color:#fee7e6}.mw-parser-output .ambox-delete{border-left:10px solid #b32424}.mw-parser-output .ambox-content{border-left:10px solid #f28500}.mw-parser-output .ambox-style{border-left:10px solid #fc3}.mw-parser-output .ambox-move{border-left:10px solid #9932cc}.mw-parser-output .ambox-protection{border-left:10px solid #a2a9b1}.mw-parser-output .ambox .mbox-text{border:none;padding:0.25em 0.5em;width:100%}.mw-parser-output .ambox .mbox-image{border:none;padding:2px 0 2px 0.5em;text-align:center}.mw-parser-output .ambox .mbox-imageright{border:none;padding:2px 0.5em 2px 0;text-align:center}.mw-parser-output .ambox .mbox-empty-cell{border:none;padding:0;width:1px}.mw-parser-output .ambox .mbox-image-div{width:52px}@media(min-width:720px){.mw-parser-output .ambox{margin:0 10%}}@media print{body.ns-0 .mw-parser-output .ambox{display:none!important}}
/* end https://en.wikipedia.org/ */
</style><style data-mw-deduplicate="TemplateStyles:r1248332772">
/* start https://en.wikipedia.org/ */
.mw-parser-output .multiple-issues-text{width:95%;margin:0.2em 0}.mw-parser-output .multiple-issues-text>.mw-collapsible-content{margin-top:0.3em}.mw-parser-output .compact-ambox .ambox{border:none;border-collapse:collapse;background-color:transparent;margin:0 0 0 1.6em!important;padding:0!important;width:auto;display:block}body.mediawiki .mw-parser-output .compact-ambox .ambox.mbox-small-left{font-size:100%;width:auto;margin:0}.mw-parser-output .compact-ambox .ambox .mbox-text{padding:0!important;margin:0!important}.mw-parser-output .compact-ambox .ambox .mbox-text-span{display:list-item;line-height:1.5em;list-style-type:disc}body.skin-minerva .mw-parser-output .multiple-issues-text>.mw-collapsible-toggle,.mw-parser-output .compact-ambox .ambox .mbox-image,.mw-parser-output .compact-ambox .ambox .mbox-imageright,.mw-parser-output .compact-ambox .ambox .mbox-empty-cell,.mw-parser-output .compact-ambox .hide-when-compact{display:none}
/* end https://en.wikipedia.org/ */
</style>
<p>In <a href="Computer_programming" title="Computer programming">computer programming</a>, the <b>scope</b> of a <a href="Name_binding" title="Name binding">name binding</a> (an association of a name to an entity, such as a <a href="Variable_(programming)" class="mw-redirect" title="Variable (programming)">variable</a>) is the part of a <a href="Computer_program" title="Computer program">program</a> where the name binding is valid; that is, where the name can be used to refer to the <a href="Entity" title="Entity">entity</a>. In other parts of the program, the name may refer to a different entity (it may have a different binding), or to nothing at all (it may be unbound). Scope helps prevent <a href="Name_collision" title="Name collision">name collisions</a> by allowing the same name to refer to different objects – as long as the names have separate scopes. The scope of a name binding is also known as the <b>visibility</b> of an entity, particularly in older or more technical literature—this is in relation to the referenced entity, not the referencing name.
</p><p>The term "scope" is also used to refer to the set of <i>all</i> name bindings that are valid within a part of a program or at a given point in a program, which is more correctly referred to as <i>context</i> or <i>environment</i>.<sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span class="cite-bracket">[</span>a<span class="cite-bracket">]</span></a></sup>
</p><p>Strictly speaking<sup id="cite_ref-2" class="reference"><a href="#cite_note-2"><span class="cite-bracket">[</span>b<span class="cite-bracket">]</span></a></sup> and in practice for most <a href="Programming_language" title="Programming language">programming languages</a>, "part of a program" refers to a portion of <a href="Source_code" title="Source code">source code</a> (area of text), and is known as <b>lexical scope</b>. In some languages, however, "part of a program" refers to a portion of <a href="Runtime_(program_lifecycle_phase)" class="mw-redirect" title="Runtime (program lifecycle phase)">run time</a> (period during <a href="Execution_(computing)" title="Execution (computing)">execution</a>), and is known as <b>dynamic scope</b>. Both of these terms are somewhat misleading—they misuse technical terms, as discussed in the <a href="#Definition">definition</a>—but the distinction itself is accurate and precise, and these are the standard respective terms. Lexical scope is the main focus of this article, with dynamic scope understood by contrast with lexical scope.
</p><p>In most cases, name resolution based on lexical scope is relatively straightforward to use and to implement, as in use one can read backwards in the source code to determine to which entity a name refers, and in <a href="Programming_language_implementation" title="Programming language implementation">implementation</a> one can maintain a list of names and contexts when <a href="Compiling" class="mw-redirect" title="Compiling">compiling</a> or <a href="Interpreter_(computing)" title="Interpreter (computing)">interpreting</a> a program. Difficulties arise in <a href="Name_masking" class="mw-redirect" title="Name masking">name masking</a>, <a href="Forward_declaration" title="Forward declaration">forward declarations</a>, and <a href="Variable_hoisting" class="mw-redirect" title="Variable hoisting">hoisting</a>, while considerably subtler ones arise with <a href="Non-local_variable" title="Non-local variable">non-local variables</a>, particularly in <a href="Closure_(computer_programming)" title="Closure (computer programming)">closures</a>.
</p>
<meta property="mw:PageProp/toc">
<div class="mw-heading mw-heading2"><h2 id="Definition">Definition</h2></div>
<p>The strict definition of the (lexical) "scope" of a name (<a href="Identifier" title="Identifier">identifier</a>) is unambiguous: lexical scope is "the portion of source code in which a binding of a name with an entity applies". This is virtually unchanged from its 1960 definition in the specification of <a href="ALGOL_60" title="ALGOL 60">ALGOL 60</a>. Representative language specifications follow:
</p>
<dl><dt>ALGOL 60 (1960)<sup id="cite_ref-RALA60_2.7_3-0" class="reference"><a href="#cite_note-RALA60_2.7-3"><span class="cite-bracket">[</span>1<span class="cite-bracket">]</span></a></sup></dt>
<dd>The following kinds of quantities are distinguished: simple variables, arrays, labels, switches, and procedures. The scope of a quantity is the set of statements and expressions in which the declaration of the identifier associated with that quantity is valid.</dd>
<dt><a href="C_(programming_language)" title="C (programming language)">C</a> (2007)<sup id="cite_ref-4" class="reference"><a href="#cite_note-4"><span class="cite-bracket">[</span>2<span class="cite-bracket">]</span></a></sup></dt>
<dd>An identifier can denote an object; a function; a tag or a member of a structure, union, or enumeration; a <a href="Typedef" title="Typedef">typedef</a> name; a label name; a macro name; or a macro parameter. The same identifier can denote different entities at different points in the program. [...] For each different entity that an identifier designates, the identifier is <i>visible</i> (i.e., can be used) only within a region of program text called its <i>scope.</i></dd>
<dt><a href="Go_(programming_language)" title="Go (programming language)">Go</a> (2013)<sup id="cite_ref-go_5-0" class="reference"><a href="#cite_note-go-5"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup></dt>
<dd>A declaration binds a non-blank identifier to a constant, type, variable, function, label, or package. [...] The scope of a declared identifier is the extent of source text in which the identifier denotes the specified constant, type, variable, function, label, or package.</dd></dl>
<p>Most commonly "scope" refers to when a given name can refer to a given <a href="Variable_(programming)" class="mw-redirect" title="Variable (programming)">variable</a>—when a <a href="Declaration_(computer_programming)" title="Declaration (computer programming)">declaration</a> has effect—but can also apply to other entities, such as functions, types, classes, <a href="Label_(computer_science)" title="Label (computer science)">labels</a>, constants, and enumerations.
</p>
<div class="mw-heading mw-heading3"><h3 id="Lexical_scope_vs._dynamic_scope">Lexical scope vs. dynamic scope</h3></div>
<p>A fundamental distinction in scope is what "part of a program" means. In languages with <b>lexical scope</b> (also called <b>static scope</b>), name resolution depends on the location in the source code and the <i>lexical context</i> (also called <i>static context</i>), which is defined by where the named variable or function is defined. In contrast, in languages with <b>dynamic scope,</b> the name resolution depends upon the <a href="Program_state" class="mw-redirect" title="Program state">program state</a> when the name is encountered which is determined by the <i>execution context</i> (also called <i>runtime context</i>, <i>calling context</i> or <i>dynamic context</i>). In practice, with lexical scope a name is resolved by searching the local lexical context, then if that fails, by searching the outer lexical context, and so on; whereas with dynamic scope, a name is resolved by searching the local execution context, then if that fails, by searching the outer execution context, and so on, progressing up the call stack.<sup id="cite_ref-Borning_6-0" class="reference"><a href="#cite_note-Borning-6"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup>
</p><p>Most modern languages use lexical scope for variables and functions, though dynamic scope is used in some languages, notably some dialects of Lisp, some "scripting" languages, and some <a href="Template_language" class="mw-redirect" title="Template language">template languages</a>.<sup id="cite_ref-7" class="reference"><a href="#cite_note-7"><span class="cite-bracket">[</span>c<span class="cite-bracket">]</span></a></sup> Perl 5 offers both lexical and dynamic scope. Functions that use lexically scoped variables are known as <a href="Closure_(computer_science)" class="mw-redirect" title="Closure (computer science)">closures</a>.
</p><p>Lexical resolution can be determined at <a href="Compile_time" title="Compile time">compile time</a>, and is also known as <i>early binding</i>, while dynamic resolution can in general only be determined at <a href="Run_time_(program_lifecycle_phase)" class="mw-redirect" title="Run time (program lifecycle phase)">run time</a>, and thus is known as <i>late binding</i>.
</p>
<div class="mw-heading mw-heading3"><h3 id="Related_concepts">Related concepts</h3></div>
<p>In <a href="Object-oriented_programming" title="Object-oriented programming">object-oriented programming</a>, <a href="Dynamic_dispatch" title="Dynamic dispatch">dynamic dispatch</a> selects an object <a href="Method_(computer_programming)" title="Method (computer programming)">method</a> at runtime, though whether the actual name binding is done at compile time or run time depends on the language. De facto dynamic scope is common in <a href="Macro_(computer_science)" title="Macro (computer science)">macro languages</a>, which do not directly do name resolution, but instead expand in place.
</p><p>Some programming frameworks like <a href="AngularJS#Scope" title="AngularJS">AngularJS</a> use the term "scope" to mean something entirely different than how it is used in this article. In those frameworks, the scope is just an object of the programming language that they use (<a href="JavaScript" title="JavaScript">JavaScript</a> in case of AngularJS) that is used in certain ways by the framework to emulate dynamic scope in a language that uses lexical scope for its variables. Those <a href="AngularJS#Scope" title="AngularJS">AngularJS scopes</a> can themselves be in context or not in context (using the usual meaning of the term) in any given part of the program, following the usual rules of variable scope of the language like any other object, and using their own <a href="Inheritance_(object-oriented_programming)" title="Inheritance (object-oriented programming)">inheritance</a> and <a href="Transclusion" title="Transclusion">transclusion</a> rules. In the context of AngularJS, sometimes the term "$scope" (with a dollar sign) is used to avoid confusion, but using the dollar sign in variable names is often discouraged by the style guides.<sup id="cite_ref-js-conventions_8-0" class="reference"><a href="#cite_note-js-conventions-8"><span class="cite-bracket">[</span>5<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="Use">Use</h2></div>
<p>Scope is an important component of <a href="Name_resolution_(programming_languages)" title="Name resolution (programming languages)">name resolution</a>,<sup id="cite_ref-9" class="reference"><a href="#cite_note-9"><span class="cite-bracket">[</span>d<span class="cite-bracket">]</span></a></sup> which is in turn fundamental to <a href="Formal_semantics_of_programming_languages" class="mw-redirect" title="Formal semantics of programming languages">language semantics</a>. Name resolution (including scope) varies between programming languages, and within a programming language, varies by type of entity; the rules for scope are called <b>scope rules</b> (or <b>scoping rules</b>). Together with <a href="Namespaces" class="mw-redirect" title="Namespaces">namespaces</a>, scope rules are crucial in <a href="Modular_programming" title="Modular programming">modular programming</a>, so a change in one part of the program does not break an unrelated part.
</p>
<div class="mw-heading mw-heading2"><h2 id="Overview">Overview</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1236090951">
/* start https://en.wikipedia.org/ */
.mw-parser-output .hatnote{font-style:italic}.mw-parser-output div.hatnote{padding-left:1.6em;margin-bottom:0.5em}.mw-parser-output .hatnote i{font-style:normal}.mw-parser-output .hatnote+link+.hatnote{margin-top:-0.5em}@media print{body.ns-0 .mw-parser-output .hatnote{display:none!important}}
/* end https://en.wikipedia.org/ */
</style><div role="note" class="hatnote navigation-not-searchable">See also: <a href="Variable_(computer_science)#Scope_and_extent" title="Variable (computer science)">Variable (computer science) § Scope and extent</a></div>
<p>When discussing scope, there are three basic concepts: <i>scope,</i> <i>extent,</i> and <i>context.</i> "Scope" and "context" in particular are frequently confused: scope is a property of a name binding, while context is a property of a part of a program, that is either a portion of source code (<i>lexical context</i> or <i>static context</i>) or a portion of <a href="Run_time_(program_lifecycle_phase)" class="mw-redirect" title="Run time (program lifecycle phase)">run time</a> (<i>execution context,</i> <i>runtime context,</i> <i>calling context</i> or <i>dynamic context</i>). Execution context consists of lexical context (at the current execution point) plus additional runtime state such as the <a href="Call_stack" title="Call stack">call stack</a>.<sup id="cite_ref-10" class="reference"><a href="#cite_note-10"><span class="cite-bracket">[</span>e<span class="cite-bracket">]</span></a></sup> Strictly speaking, during execution a program enters and exits various name bindings' scopes, and at a point in execution name bindings are "in context" or "not in context", hence name bindings "come into context" or "go out of context" as the program execution enters or exits the scope.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11"><span class="cite-bracket">[</span>f<span class="cite-bracket">]</span></a></sup> However, in practice usage is much looser.
</p><p>Scope is a source-code level concept, and a property of name bindings, particularly variable or function name bindings—names in the source code are <a href="Reference_(computer_science)" title="Reference (computer science)">references</a> to entities in the program—and is part of the behavior of a compiler or interpreter of a language. As such, issues of scope are similar to <a href="Pointer_(computer_programming)" title="Pointer (computer programming)">pointers</a>, which are a type of reference used in programs more generally. Using the value of a variable when the name is in context but the variable is uninitialized is analogous to dereferencing (accessing the value of) a <a href="Wild_pointer" class="mw-redirect" title="Wild pointer">wild pointer</a>, as it is undefined. However, as variables are not destroyed until they go out of context, the analog of a <a href="Dangling_pointer" title="Dangling pointer">dangling pointer</a> does not exist.
</p><p>For entities such as variables, scope is a subset of <a href="Object_lifetime" title="Object lifetime">lifetime</a> (also known as <a href="Variable_(programming)" class="mw-redirect" title="Variable (programming)">extent</a>)—a name can only refer to a variable that exists (possibly with undefined value), but variables that exist are not necessarily visible: a variable may exist but be inaccessible (the value is stored but not referred to within a given context), or accessible but not via the given name, in which case it is not in context (the program is "out of the scope of the name"). In other cases "lifetime" is irrelevant—a label (named position in the source code) has lifetime identical with the program (for statically compiled languages), but may be in context or not at a given point in the program, and likewise for <a href="Static_variable" title="Static variable">static variables</a>—a <a href="Static_global_variable" class="mw-redirect" title="Static global variable">static global variable</a> is in context for the entire program, while a <a href="Static_local_variable" class="mw-redirect" title="Static local variable">static local variable</a> is only in context within a function or other local context, but both have lifetime of the entire run of the program.
</p><p>Determining which entity a name refers to is known as <a href="Name_resolution_(programming_languages)" title="Name resolution (programming languages)">name resolution</a> or <a href="Name_binding" title="Name binding">name binding</a> (particularly in <a href="Object-oriented_programming" title="Object-oriented programming">object-oriented programming</a>), and varies between languages. Given a name, the language (properly, the compiler or interpreter) checks all entities that are in context for matches; in case of ambiguity (two entities with the same name, such as a global and local variable with the same name), the name resolution rules are used to distinguish them. Most frequently, name resolution relies on an "inner-to-outer context" rule, such as the Python LEGB (Local, Enclosing, Global, Built-in) rule: names implicitly resolve to the narrowest relevant context. In some cases name resolution can be explicitly specified, such as by the <code>global</code> and <code>nonlocal</code> keywords in Python; in other cases the default rules cannot be overridden.
</p><p>When two identical names are in context at the same time, referring to different entities, one says that <i><a href="Name_masking" class="mw-redirect" title="Name masking">name masking</a></i> is occurring, where the higher-priority name (usually innermost) is "masking" the lower-priority name. At the level of variables, this is known as <a href="Variable_shadowing" title="Variable shadowing">variable shadowing</a>. Due to the potential for <a href="Logic_error" title="Logic error">logic errors</a> from masking, some languages disallow or discourage masking, raising an error or warning at compile time or run time.
</p><p>Various <a href="Programming_language" title="Programming language">programming languages</a> have various different scope rules for different kinds of declarations and names. Such scope rules have a large effect on <a href="Formal_semantics_of_programming_languages" class="mw-redirect" title="Formal semantics of programming languages">language semantics</a> and, consequently, on the behavior and correctness of programs. In languages like <a href="C%2B%2B" title="C++">C++</a>, accessing an unbound variable does not have well-defined semantics and may result in <a href="Undefined_behavior" title="Undefined behavior">undefined behavior</a>, similar to referring to a <a href="Dangling_pointer" title="Dangling pointer">dangling pointer</a>; and declarations or names used outside their scope will generate <a href="Syntax_error" title="Syntax error">syntax errors</a>.
</p><p>Scopes are frequently tied to other language constructs and determined implicitly, but many languages also offer constructs specifically for controlling scope.
</p>
<div class="mw-heading mw-heading2"><h2 id="Levels_of_scope">Levels of scope</h2></div>
<p>Scope can vary from as little as a single expression to as much as the entire program, with many possible gradations in between. The simplest scope rule is global scope—all entities are visible throughout the entire program. The most basic modular scope rule is two-level scope, with a global scope anywhere in the program, and local scope within a function. More sophisticated modular programming allows a separate module scope, where names are visible within the module (private to the module) but not visible outside it. Within a function, some languages, such as C, allow block scope to restrict scope to a subset of a function; others, notably functional languages, allow expression scope, to restrict scope to a single expression. Other scopes include file scope (notably in C) which behaves similarly to module scope, and block scope outside of functions (notably in Perl).
</p><p>A subtle issue is exactly when a scope begins and ends. In some languages, such as C, a name's scope begins at the name declaration, and thus different names declared within a given block can have different scopes. This requires declaring functions before use, though not necessarily defining them, and requires <a href="Forward_declaration" title="Forward declaration">forward declaration</a> in some cases, notably for mutual recursion. In other languages, such as Python, a name's scope begins at the start of the relevant block where the name is declared (such as the start of a function), regardless of where it is defined, so all names within a given block have the same scope. In JavaScript, the scope of a name declared with <code>let</code> or <code>const</code> begins at the name declaration, and the scope of a name declared with <code>var</code> begins at the start of the function where the name is declared, which is known as <i><a href="Variable_hoisting" class="mw-redirect" title="Variable hoisting">variable hoisting</a></i>. Behavior of names in context that have undefined value differs: in Python use of undefined names yields a runtime error, while in JavaScript undefined names declared with <code>var</code> are usable throughout the function because they are implicitly bound to the value <code>undefined</code>.
</p>
<div class="mw-heading mw-heading3"><h3 id="Expression_scope">Expression scope</h3></div>
<p>The scope of a name binding is an <a href="Expression_(computer_science)" title="Expression (computer science)">expression</a>, which is known as <b>expression scope</b>. Expression scope is available in many languages, especially <a href="Functional_programming" title="Functional programming">functional</a> languages which offer a feature called <i><a href="Let_expression" title="Let expression">let expressions</a></i> allowing a declaration's scope to be a single expression. This is convenient if, for example, an intermediate value is needed for a computation. For example, in <a href="Standard_ML" title="Standard ML">Standard ML</a>, if <code>f()</code> returns <code>12</code>, then <code><b>let val</b> x = f() <b>in</b> x * x <b>end</b></code> is an expression that evaluates to <code>144</code>, using a temporary variable named <code>x</code> to avoid calling <code>f()</code> twice. Some languages with block scope approximate this functionality by offering syntax for a block to be embedded into an expression; for example, the aforementioned Standard ML expression could be written in <a href="Perl" title="Perl">Perl</a> as <code class="mw-highlight mw-highlight-lang-perl mw-content-ltr" dir="ltr"><span class="k">do</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">my</span><span class="w"> </span><span class="nv">$x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">f</span><span class="p">();</span><span class="w"> </span><span class="nv">$x</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="nv">$x</span><span class="w"> </span><span class="p">}</span></code>, or in <a href="GNU_Compiler_Collection" title="GNU Compiler Collection">GNU C</a> as <code class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><span class="p">({</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">f</span><span class="p">();</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">x</span><span class="p">;</span><span class="w"> </span><span class="p">})</span></code>.
</p><p>In Python, auxiliary variables in generator expressions and list comprehensions (in Python 3) have expression scope.
</p><p>In C, variable names in a <a href="Function_prototype" title="Function prototype">function prototype</a> have expression scope, known in this context as <b>function protocol scope</b>. As the variable names in the prototype are not referred to (they may be different in the actual definition)—they are just dummies—these are often omitted, though they may be used for generating documentation, for instance.
</p>
<div class="mw-heading mw-heading3"><h3 id="Block_scope">Block scope</h3></div>
<p>The scope of a name binding is a <a href="Block_(programming)" title="Block (programming)">block</a>, which is known as <b>block scope</b>. Block scope is available in many, but not all, block-structured programming languages. This began with <a href="ALGOL_60" title="ALGOL 60">ALGOL 60</a>, where "[e]very declaration ... is valid only for that block.",<sup id="cite_ref-12" class="reference"><a href="#cite_note-12"><span class="cite-bracket">[</span>6<span class="cite-bracket">]</span></a></sup> and today is particularly associated with languages in the <a href="Pascal_(programming_language)" title="Pascal (programming language)">Pascal</a> and <a href="C_(programming_language)" title="C (programming language)">C</a> families and traditions. Most often this block is contained within a function, thus restricting the scope to a part of a function, but in some cases, such as Perl, the block may not be within a function.
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="nf">sum_of_squares</span><span class="p">(</span><span class="k">const</span><span class="w"> </span><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">N</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">ret</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span>
<span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o"><=</span><span class="w"> </span><span class="n">N</span><span class="p">;</span><span class="w"> </span><span class="n">n</span><span class="o">++</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">n_squared</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">n</span><span class="p">;</span>
<span class="w"> </span><span class="n">ret</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">n_squared</span><span class="p">;</span>
<span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">ret</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>A representative example of the use of block scope is the C code shown here, where two variables are scoped to the loop: the loop variable <var>n</var>, which is initialized once and incremented on each iteration of the loop, and the auxiliary variable <var>n_squared</var>, which is initialized at each iteration. The purpose is to avoid adding variables to the function scope that are only relevant to a particular block—for example, this prevents errors where the generic loop variable <var>i</var> has accidentally already been set to another value. In this example the expression <code>n * n</code> would generally not be assigned to an auxiliary variable, and the body of the loop would simply be written <code>ret += n * n</code> but in more complicated examples auxiliary variables are useful.
</p><p>Blocks are primarily used for control flow, such as with if, while, and for loops, and in these cases block scope means the scope of variable depends on the structure of a function's flow of execution. However, languages with block scope typically also allow the use of "naked" blocks, whose sole purpose is to allow fine-grained control of variable scope. For example, an auxiliary variable may be defined in a block, then used (say, added to a variable with function scope) and discarded when the block ends, or a <a href="While_loop" title="While loop">while loop</a> might be enclosed in a block that initializes variables used inside the loop that should only be initialized once.
</p><p>A subtlety of several programming languages, such as <a href="Algol_68" class="mw-redirect" title="Algol 68">Algol 68</a> and C (demonstrated in this example and standardized since <a href="C99" title="C99">C99</a>), is that block-scope variables can be declared not only within the body of the block, but also within the control statement, if any. This is analogous to function parameters, which are declared in the function declaration (before the block of the function body starts), and in scope for the whole function body. This is primarily used in <a href="For_loop" title="For loop">for loops</a>, which have an initialization statement separate from the loop condition, unlike while loops, and is a common idiom.
</p><p>Block scope can be used for shadowing. In this example, inside the block the auxiliary variable could also have been called <var>n</var>, shadowing the parameter name, but this is considered poor style due to the potential for errors. Furthermore, some descendants of C, such as Java and C#, despite having support for block scope (in that a local variable can be made to go out of context before the end of a function), do not allow one local variable to hide another. In such languages, the attempted declaration of the second <var>n</var> would result in a syntax error, and one of the <var>n</var> variables would have to be renamed.
</p><p>If a block is used to set the value of a variable, block scope requires that the variable be declared outside of the block. This complicates the use of conditional statements with <a href="Single_assignment" class="mw-redirect" title="Single assignment">single assignment</a>. For example, in Python, which does not use block scope, one may initialize a variable as such:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="k">if</span> <span class="n">c</span><span class="p">:</span>
<span class="n">a</span> <span class="o">=</span> <span class="s2">"foo"</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">a</span> <span class="o">=</span> <span class="s2">""</span>
</pre></div>
<p>where <code>a</code> is accessible after the <code>if</code> statement.
</p><p>In Perl, which has block scope, this instead requires declaring the variable prior to the block:
</p>
<div class="mw-highlight mw-highlight-lang-perl mw-content-ltr" dir="ltr"><pre><span class="k">my</span><span class="w"> </span><span class="nv">$a</span><span class="p">;</span>
<span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">c</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nv">$a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">'foo'</span><span class="p">;</span>
<span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nv">$a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">''</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>Often this is instead rewritten using multiple assignment, initializing the variable to a default value. In Python (where it is not necessary) this would be:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="n">a</span> <span class="o">=</span> <span class="s2">""</span>
<span class="k">if</span> <span class="n">c</span><span class="p">:</span>
<span class="n">a</span> <span class="o">=</span> <span class="s2">"foo"</span>
</pre></div>
<p>while in Perl this would be:
</p>
<div class="mw-highlight mw-highlight-lang-perl mw-content-ltr" dir="ltr"><pre><span class="k">my</span><span class="w"> </span><span class="nv">$a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">''</span><span class="p">;</span>
<span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">c</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nv">$a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">'foo'</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>In case of a single variable assignment, an alternative is to use the <a href="Ternary_operator" class="mw-redirect" title="Ternary operator">ternary operator</a> to avoid a block, but this is not in general possible for multiple variable assignments, and is difficult to read for complex logic.
</p><p>This is a more significant issue in C, notably for string assignment, as string initialization can automatically allocate memory, while string assignment to an already initialized variable requires allocating memory, a string copy, and checking that these are successful.
</p>
<div style="float:right;margin-left:1em" class="mw-highlight mw-highlight-lang-perl mw-content-ltr" dir="ltr"><pre><span class="p">{</span>
<span class="w"> </span><span class="k">my</span><span class="w"> </span><span class="nv">$counter</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span>
<span class="w"> </span><span class="k">sub</span><span class="w"> </span><span class="nf">increment_counter</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="o">++</span><span class="nv">$counter</span><span class="p">;</span>
<span class="w"> </span><span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>Some languages allow the concept of block scope to be applied, to varying extents, outside of a function. For example, in the Perl snippet at right, <code>$counter</code> is a variable name with block scope (due to the use of the <code>my</code> keyword), while <code>increment_counter</code> is a function name with global scope. Each call to <code>increment_counter</code> will increase the value of <code>$counter</code> by one, and return the new value. Code outside of this block can call <code>increment_counter</code>, but cannot otherwise obtain or alter the value of <code>$counter</code>. This idiom allows one to define closures in Perl.
</p>
<div class="mw-heading mw-heading3"><h3 id="Function_scope">Function scope</h3></div>
<p>When the scope of variables declared within a function does not extend beyond that function, this is known as <b>function scope</b>.<sup id="cite_ref-13" class="reference"><a href="#cite_note-13"><span class="cite-bracket">[</span>7<span class="cite-bracket">]</span></a></sup> Function scope is available in most programming languages which offer a way to create a <i><a href="Local_variable" title="Local variable">local variable</a></i> in a function or <a href="Subroutine" class="mw-redirect" title="Subroutine">subroutine</a>: a variable whose scope ends (that goes out of context) when the function returns. In most cases the lifetime of the variable is the duration of the function call—it is an <a href="Automatic_variable" title="Automatic variable">automatic variable</a>, created when the function starts (or the variable is declared), destroyed when the function returns—while the scope of the variable is within the function, though the meaning of "within" depends on whether scope is lexical or dynamic. However, some languages, such as C, also provide for <a href="Static_local_variable" class="mw-redirect" title="Static local variable">static local variables</a>, where the lifetime of the variable is the entire lifetime of the program, but the variable is only in context when inside the function. In the case of static local variables, the variable is created when the program initializes, and destroyed only when the program terminates, as with a <a href="Static_global_variable" class="mw-redirect" title="Static global variable">static global variable</a>, but is only in context within a function, like an automatic local variable.
</p><p>Importantly, in lexical scope a variable with function scope has scope only within the <i>lexical context</i> of the function: it goes out of context when another function is called within the function, and comes back into context when the function returns—called functions have no access to the local variables of calling functions, and local variables are only in context within the body of the function in which they are declared. By contrast, in dynamic scope, the scope extends to the <i>execution context</i> of the function: local variables <i>stay in context</i> when another function is called, only going out of context when the defining function ends, and thus local variables are in context of the function in which they are defined <i>and all called functions</i>. In languages with lexical scope and <a href="Nested_function" title="Nested function">nested functions</a>, local variables are in context for nested functions, since these are within the same lexical context, but not for other functions that are not lexically nested. A local variable of an enclosing function is known as a <a href="Non-local_variable" title="Non-local variable">non-local variable</a> for the nested function. Function scope is also applicable to <a href="Anonymous_function" title="Anonymous function">anonymous functions</a>.
</p>
<div style="float:right;margin-left:1em" class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="k">def</span> <span class="nf">square</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">return</span> <span class="n">n</span> <span class="o">*</span> <span class="n">n</span>
<span class="k">def</span> <span class="nf">sum_of_squares</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="n">total</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">while</span> <span class="n">i</span> <span class="o"><=</span> <span class="n">n</span><span class="p">:</span>
<span class="n">total</span> <span class="o">+=</span> <span class="n">square</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="k">return</span> <span class="n">total</span>
</pre></div>
<p>For example, in the snippet of Python code on the right, two functions are defined: <code>square</code> and <code>sum_of_squares</code>. <code>square</code> computes the square of a number; <code>sum_of_squares</code> computes the sum of all squares up to a number. (For example, <code>square(4)</code> is 4<sup>2</sup> = <code>16</code>, and <code>sum_of_squares(4)</code> is 0<sup>2</sup> + 1<sup>2</sup> + 2<sup>2</sup> + 3<sup>2</sup> + 4<sup>2</sup> = <code>30</code>.)
</p><p>Each of these functions has a variable named <var>n</var> that represents the argument to the function. These two <var>n</var> variables are completely separate and unrelated, despite having the same name, because they are lexically scoped local variables with function scope: each one's scope is its own, lexically separate function and thus, they don't overlap. Therefore, <code>sum_of_squares</code> can call <code>square</code> without its own <var>n</var> being altered. Similarly, <code>sum_of_squares</code> has variables named <var>total</var> and <var>i</var>; these variables, because of their limited scope, will not interfere with any variables named <var>total</var> or <var>i</var> that might belong to any other function. In other words, there is no risk of a <i>name collision</i> between these names and any unrelated names, even if they are identical.
</p><p>No name masking is occurring: only one variable named <var>n</var> is in context at any given time, as the scopes do not overlap. By contrast, were a similar fragment to be written in a language with dynamic scope, the <var>n</var> in the calling function would remain in context in the called function—the scopes would overlap—and would be masked ("shadowed") by the new <var>n</var> in the called function.
</p><p>Function scope is significantly more complicated if functions are first-class objects and can be created locally to a function and then returned. In this case any variables in the nested function that are not local to it (unbound variables in the function definition, that resolve to variables in an enclosing context) create a <a href="Closure_(computer_science)" class="mw-redirect" title="Closure (computer science)">closure</a>, as not only the function itself, but also its context (of variables) must be returned, and then potentially called in a different context. This requires significantly more support from the compiler, and can complicate <a href="Program_analysis" title="Program analysis">program analysis</a>.
</p>
<div class="mw-heading mw-heading3"><h3 id="File_scope">File scope</h3></div>
<p>The scope of a name binding is a file, which is known as <b>file scope</b>. File scope is largely particular to C (and C++), where scope of variables and functions declared at the top level of a file (not within any function) is for the entire file—or rather for C, from the declaration until the end of the source file, or more precisely <a href="Translation_unit_(programming)" title="Translation unit (programming)">translation unit</a> (internal linking). This can be seen as a form of module scope, where modules are identified with files, and in more modern languages is replaced by an explicit module scope. Due to the presence of include statements, which add variables and functions to the internal context and may themselves call further include statements, it can be difficult to determine what is in context in the body of a file.
</p><p>In the C code snippet above, the function name <code>sum_of_squares</code> has global scope (in C, extern linkage). Adding <code class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><span class="k">static</span></code> to the function signature would result in file scope (internal linkage).
</p>
<div class="mw-heading mw-heading3"><h3 id="Module_scope">Module scope</h3></div>
<p>The scope of a name binding is a module, which is known as <b>module scope</b>. Module scope is available in <a href="Modular_programming" title="Modular programming">modular programming languages</a> where modules (which may span various files) are the basic unit of a complex program, as they allow <a href="Information_hiding" title="Information hiding">information hiding</a> and exposing a limited interface. Module scope was pioneered in the <a href="Modula" title="Modula">Modula</a> family of languages, and Python (which was influenced by Modula) is a representative contemporary example.
</p><p>In some <a href="Object-oriented_programming" title="Object-oriented programming">object-oriented programming</a> languages that lack direct support for modules, such as C++ before <a href="C%2B%2B20" title="C++20">C++20</a>,<sup id="cite_ref-14" class="reference"><a href="#cite_note-14"><span class="cite-bracket">[</span>8<span class="cite-bracket">]</span></a></sup> a similar structure is instead provided by the class hierarchy, where classes are the basic unit of the program, and a class can have private methods. This is properly understood in the context of <a href="Dynamic_dispatch" title="Dynamic dispatch">dynamic dispatch</a> rather than name resolution and scope, though they often play analogous roles. In some cases both these facilities are available, such as in Python, which has both modules and classes, and code organization (as a module-level function or a conventionally private method) is a choice of the programmer.
</p>
<div class="mw-heading mw-heading3"><h3 id="Global_scope">Global scope</h3></div>
<p>The scope of a name binding is an entire program, which is known as <b>global scope</b>. Variable names with global scope—called <i><a href="Global_variables" class="mw-redirect" title="Global variables">global variables</a></i>—are frequently considered bad practice, at least in some languages, due to the possibility of name collisions and unintentional masking, together with poor modularity, and function scope or block scope are considered preferable. However, global scope is typically used (depending on the language) for various other sorts of names, such as names of functions, names of <a href="Class_(computer_programming)" title="Class (computer programming)">classes</a> and names of other <a href="Data_type" title="Data type">data types</a>. In these cases mechanisms such as <a href="Namespaces" class="mw-redirect" title="Namespaces">namespaces</a> are used to avoid collisions.
</p>
<div class="mw-heading mw-heading2"><h2 id="Lexical_scope_vs._dynamic_scope_2">Lexical scope vs. dynamic scope </h2></div>
<p>The use of local variables — of variable names with limited scope, that only exist within a specific function — helps avoid the risk of a name collision between two identically named variables. However, there are two very different approaches to answering this question: What does it mean to be "within" a function?
</p><p>In <b>lexical scope</b> (or <b>lexical scoping</b>; also called <b>static scope</b> or <b>static scoping</b>), if a variable name's scope is a certain function, then its scope is the program text of the function definition: within that text, the variable name exists, and is bound to the variable's value, but outside that text, the variable name does not exist. By contrast, in <b>dynamic scope</b> (or <b>dynamic scoping</b>), if a variable name's scope is a certain function, then its scope is the time-period during which the function is executing: while the function is running, the variable name exists, and is bound to its value, but after the function returns, the variable name does not exist. This means that if function <code>f</code> invokes a separately defined function <code>g</code>, then under lexical scope, function <code>g</code> does <i>not</i> have access to <code>f</code>'s local variables (assuming the text of <code>g</code> is not inside the text of <code>f</code>), while under dynamic scope, function <code>g</code> <i>does</i> have access to <code>f</code>'s local variables (since <code>g</code> is invoked during the invocation of <code>f</code>).
</p>
<div style="float:right;margin-left:1em" class="mw-highlight mw-highlight-lang-console mw-content-ltr" dir="ltr"><pre><span class="gp">$ </span><span class="c1"># bash language</span>
<span class="gp">$ </span><span class="nv">x</span><span class="o">=</span><span class="m">1</span>
<span class="gp">$ </span><span class="k">function</span><span class="w"> </span>g<span class="o">()</span><span class="w"> </span><span class="o">{</span><span class="w"> </span><span class="nb">echo</span><span class="w"> </span><span class="nv">$x</span><span class="w"> </span><span class="p">;</span><span class="w"> </span><span class="nv">x</span><span class="o">=</span><span class="m">2</span><span class="w"> </span><span class="p">;</span><span class="w"> </span><span class="o">}</span>
<span class="gp">$ </span><span class="k">function</span><span class="w"> </span>f<span class="o">()</span><span class="w"> </span><span class="o">{</span><span class="w"> </span><span class="nb">local</span><span class="w"> </span><span class="nv">x</span><span class="o">=</span><span class="m">3</span><span class="w"> </span><span class="p">;</span><span class="w"> </span>g<span class="w"> </span><span class="p">;</span><span class="w"> </span><span class="o">}</span>
<span class="gp">$ </span>f<span class="w"> </span><span class="c1"># does this print 1, or 3?</span>
<span class="go">3</span>
<span class="gp">$ </span><span class="nb">echo</span><span class="w"> </span><span class="nv">$x</span><span class="w"> </span><span class="c1"># does this print 1, or 2?</span>
<span class="go">1</span>
</pre></div>
<p>Consider, for example, the program on the right. The first line, <code class="mw-highlight mw-highlight-lang-bash mw-content-ltr" dir="ltr"><span class="nv">x</span><span class="o">=</span><span class="m">1</span></code>, creates a global variable <code>x</code> and initializes it to <code>1</code>. The second line, <code class="mw-highlight mw-highlight-lang-bash mw-content-ltr" dir="ltr"><span class="k">function</span><span class="w"> </span>g<span class="o">()</span><span class="w"> </span><span class="o">{</span><span class="w"> </span><span class="nb">echo</span><span class="w"> </span><span class="nv">$x</span><span class="w"> </span><span class="p">;</span><span class="w"> </span><span class="nv">x</span><span class="o">=</span><span class="m">2</span><span class="w"> </span><span class="p">;</span><span class="w"> </span><span class="o">}</span></code>, defines a function <code>g</code> that prints out ("echoes") the current value of <code>x</code>, and then sets <code>x</code> to <code>2</code> (overwriting the previous value). The third line, <code class="mw-highlight mw-highlight-lang-bash mw-content-ltr" dir="ltr"><span class="k">function</span><span class="w"> </span>f<span class="o">()</span><span class="w"> </span><span class="o">{</span><span class="w"> </span><span class="nb">local</span><span class="w"> </span><span class="nv">x</span><span class="o">=</span><span class="m">3</span><span class="w"> </span><span class="p">;</span><span class="w"> </span>g<span class="w"> </span><span class="p">;</span><span class="w"> </span><span class="o">}</span></code> defines a function <code>f</code> that creates a local variable <code>x</code> (hiding the identically named global variable) and initializes it to <code>3</code>, and then calls <code>g</code>. The fourth line, <code class="mw-highlight mw-highlight-lang-bash mw-content-ltr" dir="ltr">f</code>, calls <code>f</code>. The fifth line, <code class="mw-highlight mw-highlight-lang-bash mw-content-ltr" dir="ltr"><span class="nb">echo</span><span class="w"> </span><span class="nv">$x</span></code>, prints out the current value of <code>x</code>.
</p><p>
The scope rules determine what this program prints. If the language of this program is one that uses lexical scope, then <code>g</code> prints and modifies the global variable <code>x</code> (because <code>g</code> is defined outside <code>f</code>), so the program prints <code>1</code> and then <code>2</code>. By contrast, if this language uses dynamic scope, then <code>g</code> prints and modifies <code>f</code>'s local variable <code>x</code> (because <code>g</code> is called from within <code>f</code>), so the program prints <code>3</code> and then <code>1</code>. (As it happens, the language of the program is <a href="Bash_(Unix_shell)" title="Bash (Unix shell)">Bash</a>, which uses dynamic scope; so the program prints <code>3</code> and then <code>1</code>. If the same code was run with <a href="KornShell" title="KornShell">ksh93</a> which uses lexical scope, the results would be different.)</p><div style="clear:both;" class=""></div>
<div class="mw-heading mw-heading2"><h2 id="Lexical_scope">Lexical scope</h2></div>
<p>With <b>lexical scope</b>, a name always refers to its lexical context. This is a property of the program text and is made independent of the runtime <a href="Call_stack" title="Call stack">call stack</a> by the language implementation. Because this matching only requires analysis of the static program text, this type of scope is also called <b>static scope</b>. Lexical scope is standard in all <a href="ALGOL" title="ALGOL">ALGOL</a>-based languages such as <a href="Pascal_(programming_language)" title="Pascal (programming language)">Pascal</a>, <a href="Modula-2" title="Modula-2">Modula-2</a> and <a href="Ada_(programming_language)" title="Ada (programming language)">Ada</a> as well as in modern functional languages such as <a href="ML_(programming_language)" title="ML (programming language)">ML</a> and <a href="Haskell_(programming_language)" class="mw-redirect" title="Haskell (programming language)">Haskell</a>. It is also used in the <a href="C_(programming_language)" title="C (programming language)">C language</a> and its syntactic and semantic relatives, although with different kinds of limitations. Static scope allows the programmer to reason about object references such as parameters, variables, constants, types, functions, etc., as simple name substitutions. This makes it much easier to make modular code and reason about it, since the local naming structure can be understood in isolation. In contrast, dynamic scope forces the programmer to anticipate all possible execution contexts in which the module's code may be invoked.
</p>
<div style="float:right;margin-left:1em" class="mw-highlight mw-highlight-lang-pascal mw-content-ltr" dir="ltr"><pre><span class="k">program</span><span class="w"> </span><span class="n">P</span><span class="o">;</span>
<span class="k">var</span><span class="w"> </span><span class="n">I</span><span class="o">:</span><span class="kt">integer</span><span class="o">;</span>
<span class="w"> </span><span class="n">K</span><span class="o">:</span><span class="kt">char</span><span class="o">;</span>
<span class="w"> </span><span class="k">procedure</span><span class="w"> </span><span class="nf">A</span><span class="o">;</span>
<span class="w"> </span><span class="k">var</span><span class="w"> </span><span class="n">K</span><span class="o">:</span><span class="kt">real</span><span class="o">;</span>
<span class="w"> </span><span class="n">L</span><span class="o">:</span><span class="kt">integer</span><span class="o">;</span>
<span class="w"> </span><span class="k">procedure</span><span class="w"> </span><span class="nf">B</span><span class="o">;</span>
<span class="w"> </span><span class="k">var</span><span class="w"> </span><span class="n">M</span><span class="o">:</span><span class="kt">real</span><span class="o">;</span>
<span class="w"> </span><span class="k">begin</span>
<span class="w"> </span><span class="cm">(*scope P+A+B*)</span>
<span class="w"> </span><span class="k">end</span><span class="o">;</span>
<span class="w"> </span><span class="cm">(*scope P+A*)</span>
<span class="w"> </span><span class="k">end</span><span class="o">;</span>
<span class="w"> </span><span class="cm">(*scope P*)</span>
<span class="k">end</span><span class="o">.</span>
</pre></div>
<p>For example, Pascal is lexically scoped. Consider the Pascal program fragment at right. The variable <code>I</code> is visible at all points, because it is never hidden by another variable of the same name. The <code>char</code> variable <code>K</code> is visible only in the main program because it is hidden by the <code>real</code> variable <code>K</code> visible only in procedures <code>A</code> and <code>B</code>. Variable <code>L</code> is also visible only in procedure <code>A</code> and <code>B</code> but it does not hide any other variable. Variable <code>M</code> is only visible in procedure <code>B</code> and therefore not accessible either from procedure <code>A</code> or the main program. Also, procedure <code>B</code> is visible only in procedure <code>A</code> and can therefore not be called from the main program. There could have been another procedure named<code>B</code> declared in the program outside of procedure <code>B</code>. The place in the program where "<code>B</code>" is mentioned then determines which of the two procedures named <code>B</code> it represents, analogous with the scope of variables.
</p><p>Correct implementation of lexical scope in languages with <a href="First-class_function" title="First-class function">first-class</a> <a href="Nested_function" title="Nested function">nested functions</a> is not trivial, as it requires each function value to carry with it a record of the values of the variables that it depends on (the pair of the function and this context is called a <a href="Closure_(computer_science)" class="mw-redirect" title="Closure (computer science)">closure</a>). Depending on implementation and <a href="Computer_architecture" title="Computer architecture">computer architecture</a>, variable <a href="Lookup" class="mw-redirect" title="Lookup">lookup</a> <i>may</i> become slightly inefficient when very deeply lexically <a href="Nesting_(computing)" title="Nesting (computing)">nested</a> functions are used, although there are well-known techniques to mitigate this.<sup id="cite_ref-15" class="reference"><a href="#cite_note-15"><span class="cite-bracket">[</span>9<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-16" class="reference"><a href="#cite_note-16"><span class="cite-bracket">[</span>10<span class="cite-bracket">]</span></a></sup> Also, for nested functions that only refer to their own arguments and (immediately) local variables, all relative locations can be known at <a href="Compile_time" title="Compile time">compile time</a>. No overhead at all is therefore incurred when using that type of nested function. The same applies to particular parts of a program where nested functions are not used, and, naturally, to programs written in a language where nested functions are not available (such as in the C language).
</p>
<div class="mw-heading mw-heading3"><h3 id="History">History</h3></div>
<p>Lexical scope was first used in the early 1960s for the imperative language <a href="ALGOL_60" title="ALGOL 60">ALGOL 60</a> and has been picked up in most other imperative languages since then.<sup id="cite_ref-Borning_6-1" class="reference"><a href="#cite_note-Borning-6"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup>
</p><p>Languages like <a href="Pascal_(programming_language)" title="Pascal (programming language)">Pascal</a> and <a href="C_(programming_language)" title="C (programming language)">C</a> have always had lexical scope, since they are both influenced by the ideas that went into <a href="ALGOL_60" title="ALGOL 60">ALGOL 60</a> and <a href="ALGOL_68" title="ALGOL 68">ALGOL 68</a> (although C did not include lexically <a href="Nested_function" title="Nested function">nested functions</a>).
</p><p><a href="Perl" title="Perl">Perl</a> is a language with dynamic scope that added static scope afterwards.
</p><p>The original <a href="Lisp_(programming_language)" title="Lisp (programming language)">Lisp</a> interpreter (1960) used dynamic scope. <i>Deep binding</i>, which approximates static (lexical) scope, was introduced around 1962 in LISP 1.5 (via the <a href="Funarg" class="mw-redirect" title="Funarg">Funarg</a> device developed by <a href="Steve_Russell_(computer_scientist)" title="Steve Russell (computer scientist)">Steve Russell</a>, working under <a href="John_McCarthy_(computer_scientist)" title="John McCarthy (computer scientist)">John McCarthy</a>).
</p><p>All early <a href="Lisp_(programming_language)" title="Lisp (programming language)">Lisps</a> used dynamic scope, when based on interpreters. In 1982, Guy L. Steele Jr. and the Common LISP Group published <i>An overview of Common LISP</i>,<sup id="cite_ref-17" class="reference"><a href="#cite_note-17"><span class="cite-bracket">[</span>11<span class="cite-bracket">]</span></a></sup> a short review of the history and the divergent implementations of Lisp up to that moment and a review of the features that a <i>Common Lisp</i> implementation should have. On page 102, we read:
</p>
<blockquote><p>Most LISP implementations are internally inconsistent in that by default the interpreter and compiler may assign different semantics to correct programs; this stems primarily from the fact that the interpreter assumes all variables to be dynamically scoped, while the compiler assumes all variables to be local unless forced to assume otherwise. This has been done for the sake of convenience and efficiency, but can lead to very subtle bugs. The definition of Common LISP avoids such anomalies by explicitly requiring the interpreter and compiler to impose identical semantics on correct programs.</p></blockquote>
<p>Implementations of Common LISP were thus required to have <a href="Common_Lisp#Lexical" title="Common Lisp">lexical scope</a>. Again, from <i>An overview of Common LISP</i>:
</p>
<blockquote><p>In addition, Common LISP offers the following facilities (most of which are borrowed from MacLisp, InterLisp or Lisp Machines Lisp): (...) Fully lexically scoped variables. The so-called "<a href="Funarg_problem" title="Funarg problem">FUNARG problem</a>"<sup id="cite_ref-18" class="reference"><a href="#cite_note-18"><span class="cite-bracket">[</span>12<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-19" class="reference"><a href="#cite_note-19"><span class="cite-bracket">[</span>13<span class="cite-bracket">]</span></a></sup> is completely solved, in both the downward and upward cases.</p></blockquote>
<p>By the same year in which <i>An overview of Common LISP</i> was published (1982), initial designs (also by Guy L. Steele Jr.) of a compiled, lexically scoped Lisp, called <i><a href="History_of_the_Scheme_programming_language" title="History of the Scheme programming language">Scheme</a></i> had been published and compiler implementations were being attempted. At that time, lexical scope in Lisp was commonly feared to be inefficient to implement. In <i>A History of T</i>,<sup id="cite_ref-20" class="reference"><a href="#cite_note-20"><span class="cite-bracket">[</span>14<span class="cite-bracket">]</span></a></sup> Olin Shivers writes:
</p>
<blockquote><p><i>All</i> serious Lisps in production use at that time were dynamically scoped. No one who hadn't carefully read the Rabbit<sup id="cite_ref-21" class="reference"><a href="#cite_note-21"><span class="cite-bracket">[</span>15<span class="cite-bracket">]</span></a></sup> thesis (written by Guy Lewis Steele Jr. in 1978) believed lexical scope would fly; even the few people who <i>had</i> read it were taking a bit of a leap of faith that this was going to work in serious production use.</p></blockquote>
<p>The term "lexical scope" dates at least to 1967,<sup id="cite_ref-22" class="reference"><a href="#cite_note-22"><span class="cite-bracket">[</span>16<span class="cite-bracket">]</span></a></sup> while the term "lexical scoping" dates at least to 1970, where it was used in <a href="Project_MAC" class="mw-redirect" title="Project MAC">Project MAC</a> to describe the scope rules of the Lisp dialect <a href="MDL_(programming_language)" title="MDL (programming language)">MDL</a> (then known as "Muddle").<sup id="cite_ref-23" class="reference"><a href="#cite_note-23"><span class="cite-bracket">[</span>17<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="Dynamic_scope">Dynamic scope</h2></div>
<p>With <b>dynamic scope</b>, a name refers to execution context. In technical terms, this means that each name has a global <a href="Stack_(data_structure)" class="mw-redirect" title="Stack (data structure)">stack</a> of bindings. Introducing a local variable with name <code>x</code> pushes a binding onto the global <code>x</code> stack (which may have been empty), which is popped off when the <a href="Control_flow" title="Control flow">control flow</a> leaves the scope. Evaluating <code>x</code> in any context always yields the top binding. Note that this cannot be done at compile-time because the binding stack only exists at <a href="Run_time_(program_lifecycle_phase)" class="mw-redirect" title="Run time (program lifecycle phase)">run-time</a>, which is why this type of scope is called <i>dynamic</i> scope.
</p><p>Dynamic scope is uncommon in modern languages.<sup id="cite_ref-Borning_6-2" class="reference"><a href="#cite_note-Borning-6"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup>
</p><p>Generally, certain <a href="Block_(programming)" title="Block (programming)">blocks</a> are defined to create bindings whose lifetime is the execution time of the block; this adds some features of static scope to the dynamic scope process. However, since a section of code can be called from many different locations and situations, it can be difficult to determine at the outset what bindings will apply when a variable is used (or if one exists at all). This can be beneficial; application of the <a href="Principle_of_least_knowledge" class="mw-redirect" title="Principle of least knowledge">principle of least knowledge</a> suggests that code avoid depending on the <i>reasons</i> for (or circumstances of) a variable's value, but simply use the value according to the variable's definition. This narrow interpretation of shared data can provide a very flexible system for adapting the behavior of a function to the current state (or policy) of the system. However, this benefit relies on careful documentation of all variables used this way as well as on careful avoidance of assumptions about a variable's behavior, and does not provide any mechanism to detect interference between different parts of a program. Some languages, like <a href="Perl" title="Perl">Perl</a> and <a href="Common_Lisp" title="Common Lisp">Common Lisp</a>, allow the programmer to choose static or dynamic scope when defining or redefining a variable. Examples of languages that use dynamic scope include <a href="Logo_(programming_language)" title="Logo (programming language)">Logo</a>, <a href="Emacs_Lisp" title="Emacs Lisp">Emacs Lisp</a>, <a href="LaTeX" title="LaTeX">LaTeX</a> and the shell languages <a href="Bash_(Unix_shell)" title="Bash (Unix shell)">bash</a>, <a href="Debian_Almquist_shell" class="mw-redirect" title="Debian Almquist shell">dash</a>, and <a href="Windows_PowerShell" class="mw-redirect" title="Windows PowerShell">PowerShell</a>.
</p><p>Dynamic scope is fairly easy to implement. To find an name's value, the program could traverse the runtime stack, checking each activation record (each function's stack frame) for a value for the name. In practice, this is made more efficient via the use of an <a href="Association_list" title="Association list">association list</a>, which is a stack of name/value pairs. Pairs are pushed onto this stack whenever declarations are made, and popped whenever variables go out of context.<sup id="cite_ref-FOOTNOTEScott20093.4_Implementing_Scope,_p._143_24-0" class="reference"><a href="#cite_note-FOOTNOTEScott20093.4_Implementing_Scope,_p._143-24"><span class="cite-bracket">[</span>18<span class="cite-bracket">]</span></a></sup> <i>Shallow binding</i> is an alternative strategy that is considerably faster, making use of a <i>central reference table</i>, which associates each name with its own stack of meanings. This avoids a linear search during run-time to find a particular name, but care should be taken to properly maintain this table.<sup id="cite_ref-FOOTNOTEScott20093.4_Implementing_Scope,_p._143_24-1" class="reference"><a href="#cite_note-FOOTNOTEScott20093.4_Implementing_Scope,_p._143-24"><span class="cite-bracket">[</span>18<span class="cite-bracket">]</span></a></sup> Note that both of these strategies assume a last-in-first-out (<a href="LIFO_(computing)" class="mw-redirect" title="LIFO (computing)">LIFO</a>) ordering to bindings for any one variable; in practice all bindings are so ordered.
</p><p>An even simpler implementation is the representation of dynamic variables with simple global variables. The local binding is performed by saving the original value in an anonymous location on the stack that is invisible to the program. When that binding scope terminates, the original value is restored from this location. In fact, dynamic scope originated in this manner. Early implementations of Lisp used this obvious strategy for implementing local variables, and the practice survives in some dialects which are still in use, such as GNU Emacs Lisp. Lexical scope was introduced into Lisp later. This is equivalent to the above shallow binding scheme, except that the central reference table is simply the global variable binding context, in which the current meaning of the variable is its global value. Maintaining global variables isn't complex. For instance, a symbol object can have a dedicated slot for its global value.
</p><p>Dynamic scope provides an excellent abstraction for <a href="Thread-local_storage" title="Thread-local storage">thread-local storage</a>, but if it is used that way it cannot be based on saving and restoring a global variable. A possible implementation strategy is for each variable to have a thread-local key. When the variable is accessed, the thread-local key is used to access the thread-local memory location (by code generated by the compiler, which knows which variables are dynamic and which are lexical). If the thread-local key does not exist for the calling thread, then the global location is used. When a variable is locally bound, the prior value is stored in a hidden location on the stack. The thread-local storage is created under the variable's key, and the new value is stored there. Further nested overrides of the variable within that thread simply save and restore this thread-local location. When the initial, outermost override's context terminates, the thread-local key is deleted, exposing the global version of the variable once again to that thread.
</p><p>With <a href="Referential_transparency" title="Referential transparency">referential transparency</a> the dynamic scope is restricted to the argument stack of the current function only, and coincides with the lexical scope.
</p>
<div class="mw-heading mw-heading3"><h3 id="Macro_expansion">Macro expansion</h3></div>
<div role="note" class="hatnote navigation-not-searchable">Main article: <a href="Macro_expansion" class="mw-redirect" title="Macro expansion">Macro expansion</a></div>
<p>In modern languages, <a href="Macro_expansion" class="mw-redirect" title="Macro expansion">macro expansion</a> in a <a href="Preprocessor" title="Preprocessor">preprocessor</a> is a key example of de facto dynamic scope. The macro language itself only transforms the source code, without resolving names, but since the expansion is done in place, when the names in the expanded text are then resolved (notably free variables), they are resolved based on where they are expanded (loosely "called"), as if dynamic scope were occurring.
</p><p>The <a href="C_preprocessor" title="C preprocessor">C preprocessor</a>, used for <a href="Macro_expansion" class="mw-redirect" title="Macro expansion">macro expansion</a>, has de facto dynamic scope, as it does not do name resolution by itself and it is independent of where the macro is defined. For example, the macro:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="cp">#define ADD_A(x) x + a</span>
</pre></div>
<p>will expand to add <code>a</code> to the passed variable, with this name only later resolved by the compiler based on where the macro <code>ADD_A</code> is "called" (properly, expanded). Properly, the C preprocessor only does <a href="Lexical_analysis" title="Lexical analysis">lexical analysis</a>, expanding the macro during the tokenization stage, but not parsing into a syntax tree or doing name resolution.
</p><p>For example, in the following code, the name <code>a</code> in the macro is resolved (after expansion) to the local variable at the expansion site:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="cp">#define ADD_A(x) x + a</span>
<span class="kt">void</span><span class="w"> </span><span class="nf">add_one</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span>
<span class="w"> </span><span class="o">*</span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">ADD_A</span><span class="p">(</span><span class="o">*</span><span class="n">x</span><span class="p">);</span>
<span class="p">}</span>
<span class="kt">void</span><span class="w"> </span><span class="nf">add_two</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span>
<span class="w"> </span><span class="o">*</span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">ADD_A</span><span class="p">(</span><span class="o">*</span><span class="n">x</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<div class="mw-heading mw-heading2"><h2 id="Qualified_names">Qualified names</h2></div>
<p>As we have seen, one of the key reasons for scope is that it helps prevent name collisions, by allowing identical names to refer to distinct things, with the restriction that the names must have separate scopes. Sometimes this restriction is inconvenient; when many different things need to be accessible throughout a program, they generally all need names with global scope, so different techniques are required to avoid name collisions.
</p><p>To address this, many languages offer mechanisms for organizing global names. The details of these mechanisms, and the terms used, depend on the language; but the general idea is that a group of names can itself be given a name — a prefix — and, when necessary, an entity can be referred to by a <i>qualified name</i> consisting of the name plus the prefix. Normally such names will have, in a sense, two sets of scopes: a scope (usually the global scope) in which the qualified name is visible, and one or more narrower scopes in which the <i>unqualified name</i> (without the prefix) is visible as well. And normally these groups can themselves be organized into groups; that is, they can be <i>nested</i>.
</p><p>Although many languages support this concept, the details vary greatly. Some languages have mechanisms, such as <i>namespaces</i> in <a href="C%2B%2B" title="C++">C++</a> and <a href="C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a>, that serve almost exclusively to enable global names to be organized into groups. Other languages have mechanisms, such as <i>packages</i> in <a href="Ada_(programming_language)" title="Ada (programming language)">Ada</a> and <i>structures</i> in <a href="Standard_ML" title="Standard ML">Standard ML</a>, that combine this with the additional purpose of allowing some names to be visible only to other members of their group. And object-oriented languages often allow classes or singleton objects to fulfill this purpose (whether or not they <i>also</i> have a mechanism for which this is the primary purpose). Furthermore, languages often meld these approaches; for example, <a href="Perl" title="Perl">Perl</a>'s packages are largely similar to C++'s namespaces, but optionally double as classes for object-oriented programming; and <a href="Java_(programming_language)" title="Java (programming language)">Java</a> organizes its variables and functions into classes, but then organizes those classes into Ada-like packages.
</p>
<div class="mw-heading mw-heading2"><h2 id="By_language">By language</h2></div>
<p>Scope rules for representative languages follow.
</p>
<div class="mw-heading mw-heading3"><h3 id="C">C</h3></div>
<div role="note" class="hatnote navigation-not-searchable">Main article: <a href="Linkage_(software)" title="Linkage (software)">Linkage (software)</a></div>
<p>In C, scope is traditionally known as <b><a href="Linkage_(software)" title="Linkage (software)">linkage</a></b> or <b>visibility</b>, particularly for variables. C is a lexically scoped language with global scope (known as <i>external linkage</i>), a form of module scope or file scope (known as <i>internal linkage</i>), and local scope (within a function); within a function scopes can further be nested via block scope. However, standard C does not support nested functions.
</p><p>The lifetime and visibility of a variable are determined by its <a href="Storage_class" class="mw-redirect" title="Storage class">storage class</a>. There are three types of lifetimes in C: static (program execution), automatic (block execution, allocated on the stack), and manual (allocated on the heap). Only static and automatic are supported for variables and handled by the compiler, while manually allocated memory must be tracked manually across different variables. There are three levels of visibility in C: external linkage (global), internal linkage (roughly file), and block scope (which includes functions); block scopes can be nested, and different levels of internal linkage is possible by use of includes. Internal linkage in C is visibility at the <a href="Translation_unit_(programming)" title="Translation unit (programming)">translation unit</a> level, namely a source file after being processed by the <a href="C_preprocessor" title="C preprocessor">C preprocessor</a>, notably including all relevant includes.
</p><p>C programs are compiled as separate <a href="Object_file" title="Object file">object files</a>, which are then linked into an executable or library via a <a href="Linker_(computing)" title="Linker (computing)">linker</a>. Thus name resolution is split across the compiler, which resolves names within a translation unit (more loosely, "compilation unit", but this is properly a different concept), and the linker, which resolves names across translation units; see <a href="Linkage_(software)" title="Linkage (software)">linkage</a> for further discussion.
</p><p>In C, variables with block scope enter context when they are declared (not at the top of the block), go out of context if any (non-nested) function is called within the block, come back into context when the function returns, and go out of context at the end of the block. In the case of automatic local variables, they are also allocated on declaration and deallocated at the end of the block, while for static local variables, they are allocated at program initialization and deallocated at program termination.
</p><p>The following program demonstrates a variable with block scope coming into context partway through the block, then exiting context (and in fact being deallocated) when the block ends:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="cp">#include</span><span class="w"> </span><span class="cpf"><stdio.h></span>
<span class="kt">int</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">'m'</span><span class="p">;</span>
<span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">"%c</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">x</span><span class="p">);</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">"%c</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">x</span><span class="p">);</span>
<span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">'b'</span><span class="p">;</span>
<span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">"%c</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">x</span><span class="p">);</span>
<span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">"%c</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">x</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<p>The program outputs:
</p>
<pre>m
m
b
m
</pre>
<p>There are other levels of scope in C.<sup id="cite_ref-25" class="reference"><a href="#cite_note-25"><span class="cite-bracket">[</span>19<span class="cite-bracket">]</span></a></sup> Variable names used in a function prototype have function prototype visibility, and exit context at the end of the function prototype. Since the name is not used, this is not useful for compilation, but may be useful for documentation. Label names for GOTO statement have function scope.
</p>
<div class="mw-heading mw-heading3"><h3 id="C++">C++</h3></div>
<p>All the variables that we intend to use in a program must have been declared with its type specifier in an earlier
point in the code, like we did in the previous code at the beginning of the body of the function main when we
declared that a, b, and result were of type int.
A variable can be either of global or local scope. A global variable is a variable declared in the main body of the
source code, outside all functions, while a local variable is one declared within the body of a function or a block.
</p><p>Modern versions <a href="Anonymous_function#C++_(since_C++11)" title="Anonymous function">allow</a> nested lexical scope.
</p>
<div class="mw-heading mw-heading3"><h3 id="Swift">Swift</h3></div>
<p><a href="Swift_(programming_language)" title="Swift (programming language)">Swift</a> has a similar rule for scopes with C++, but contains different access modifiers.
</p>
<table class="wikitable">
<tbody><tr>
<th>Modifier</th>
<th>Immediate scope</th>
<th>File</th>
<th>Containing module/package</th>
<th>Rest of the world
</th></tr>
<tr>
<td>open</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes, allows subclass
</td></tr>
<tr>
<td>public</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes, disallows subclass
</td></tr>
<tr>
<td>internal</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No
</td></tr>
<tr>
<td>fileprivate</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No
</td></tr>
<tr>
<td>private</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No
</td></tr></tbody></table>
<div class="mw-heading mw-heading3"><h3 id="Go">Go</h3></div>
<p><a href="Go_(programming_language)" title="Go (programming language)">Go</a> is lexically scoped using blocks.<sup id="cite_ref-go_5-1" class="reference"><a href="#cite_note-go-5"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading3"><h3 id="Java">Java</h3></div>
<p><a href="Java_(programming_language)" title="Java (programming language)">Java</a> is lexically scoped.
</p><p>A Java class has several kinds of variables:<sup id="cite_ref-26" class="reference"><a href="#cite_note-26"><span class="cite-bracket">[</span>20<span class="cite-bracket">]</span></a></sup>
</p>
<dl><dt>Local variables</dt>
<dd>are defined inside a method, or a particular block. These variables are local to where they were defined and lower levels. For example, a loop inside a method can use that method's local variables, but not the other way around. The loop's variables (local to that loop) are destroyed as soon as the loop ends.</dd></dl>
<dl><dt>Member variables</dt>
<dd>also called <i>fields</i> are variables declared within the class, outside of any method. By default, these variables are available for all methods within that class and also for all classes in the package.</dd></dl>
<dl><dt>Parameters</dt>
<dd>are variables in method declarations.</dd></dl>
<p>In general, a set of brackets defines a particular scope, but variables at top level within a class can differ in their behavior depending on the modifier keywords used in their definition.
The following table shows the access to members permitted by each modifier.<sup id="cite_ref-27" class="reference"><a href="#cite_note-27"><span class="cite-bracket">[</span>21<span class="cite-bracket">]</span></a></sup>
</p>
<table class="wikitable">
<tbody><tr>
<th>Modifier</th>
<th>Class</th>
<th>Package</th>
<th>Subclass</th>
<th>World
</th></tr>
<tr>
<td>public</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes
</td></tr>
<tr>
<td>protected</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No
</td></tr>
<tr>
<td>(no modifier)</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No
</td></tr>
<tr>
<td>private</td>
<td style="background:#9EFF9E;color:black;vertical-align:middle;text-align:center;" class="table-yes">Yes</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No</td>
<td style="background:#FFC7C7;color:black;vertical-align:middle;text-align:center;" class="table-no">No
</td></tr></tbody></table>
<div class="mw-heading mw-heading3"><h3 id="JavaScript">JavaScript</h3></div>
<p><a href="JavaScript" title="JavaScript">JavaScript</a> has simple <i>scope rules</i>,<sup id="cite_ref-28" class="reference"><a href="#cite_note-28"><span class="cite-bracket">[</span>22<span class="cite-bracket">]</span></a></sup> but variable initialization and name resolution rules can cause problems, and the widespread use of closures for callbacks means the lexical context of a function when defined (which is used for name resolution) can be very different from the lexical context when it is called (which is irrelevant for name resolution). JavaScript objects have name resolution for properties, but this is a separate topic.
</p><p>JavaScript has lexical scope <sup id="cite_ref-29" class="reference"><a href="#cite_note-29"><span class="cite-bracket">[</span>23<span class="cite-bracket">]</span></a></sup> nested at the function level, with the global context being the outermost context. This scope is used for both variables and for functions (meaning function declarations, as opposed to variables of <a href="Function_type" title="Function type">function type</a>).<sup id="cite_ref-30" class="reference"><a href="#cite_note-30"><span class="cite-bracket">[</span>24<span class="cite-bracket">]</span></a></sup> Block scope with the <code>let</code> and <code><a href="Const_(computer_programming)" title="Const (computer programming)">const</a></code> keywords is standard since <a href="ECMAScript" title="ECMAScript">ECMAScript</a> 6. Block scope can be produced by wrapping the entire block in a function and then executing it; this is known as the <a href="Immediately-invoked_function_expression" class="mw-redirect" title="Immediately-invoked function expression">immediately-invoked function expression</a> (IIFE) pattern.
</p><p>While JavaScript scope is simple—lexical, function-level—the associated initialization and name resolution rules are a cause of confusion. Firstly, assignment to a name not in scope defaults to creating a new global variable, not a local one. Secondly, to create a new local variable one must use the <code>var</code> keyword; the variable is then created at the top of the function, with value <code>undefined</code> and the variable is assigned its value when the assignment expression is reached:
</p>
<dl><dd>A variable with an <i>Initialiser</i> is assigned the value of its <i>AssignmentExpression</i> when the <i>VariableStatement</i> is executed, not when the variable is created.<sup id="cite_ref-31" class="reference"><a href="#cite_note-31"><span class="cite-bracket">[</span>25<span class="cite-bracket">]</span></a></sup></dd></dl>
<p>This is known as <i><a href="Variable_hoisting" class="mw-redirect" title="Variable hoisting">variable hoisting</a></i><sup id="cite_ref-32" class="reference"><a href="#cite_note-32"><span class="cite-bracket">[</span>26<span class="cite-bracket">]</span></a></sup>—the declaration, but not the initialization, is hoisted to the top of the function. Thirdly, accessing variables before initialization yields <code>undefined</code>, rather than a syntax error. Fourthly, for function declarations, the declaration and the initialization are both hoisted to the top of the function, unlike for variable initialization. For example, the following code produces a dialog with output <samp>undefined</samp>, as the local variable declaration is hoisted, shadowing the global variable, but the initialization is not, so the variable is undefined when used:
</p>
<div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span class="nx">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">1</span><span class="p">;</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">f</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">alert</span><span class="p">(</span><span class="nx">a</span><span class="p">);</span>
<span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="nx">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">2</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">f</span><span class="p">();</span>
</pre></div>
<p>Further, as functions are first-class objects in JavaScript and are frequently assigned as callbacks or returned from functions, when a function is executed, the name resolution depends on where it was originally defined (the lexical context of the definition), not the lexical context or execution context where it is called. The nested scopes of a particular function (from most global to most local) in JavaScript, particularly of a closure, used as a callback, are sometimes referred to as the <b>scope chain</b>, by analogy with the prototype chain of an object.
</p><p><a href="Closure_(computer_science)" class="mw-redirect" title="Closure (computer science)">Closures</a> can be produced in JavaScript by using nested functions, as functions are first-class objects.<sup id="cite_ref-33" class="reference"><a href="#cite_note-33"><span class="cite-bracket">[</span>27<span class="cite-bracket">]</span></a></sup> Returning a nested function from an enclosing function includes the local variables of the enclosing function as the (non-local) lexical context of the returned function, yielding a closure. For example:
</p>
<div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span class="kd">function</span><span class="w"> </span><span class="nx">newCounter</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// return a counter that is incremented on call (starting at 0)</span>
<span class="w"> </span><span class="c1">// and which returns its new value</span>
<span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="nx">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">0</span><span class="p">;</span>
<span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="nx">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kd">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nx">a</span><span class="o">++</span><span class="p">;</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">a</span><span class="p">;</span><span class="w"> </span><span class="p">};</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">b</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">c</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">newCounter</span><span class="p">();</span>
<span class="nx">alert</span><span class="p">(</span><span class="nx">c</span><span class="p">()</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s1">' '</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">c</span><span class="p">());</span><span class="w"> </span><span class="c1">// outputs "1 2"</span>
</pre></div>
<p>Closures are frequently used in JavaScript, due to being used for callbacks. Indeed, any hooking of a function in the local context as a callback or returning it from a function creates a closure if there are any unbound variables in the function body (with the context of the closure based on the nested scopes of the current lexical context, or "scope chain"); this may be accidental. When creating a callback based on parameters, the parameters must be stored in a closure, otherwise it will accidentally create a closure that refers to the variables in the enclosing context, which may change.<sup id="cite_ref-34" class="reference"><a href="#cite_note-34"><span class="cite-bracket">[</span>28<span class="cite-bracket">]</span></a></sup>
</p><p>Name resolution of properties of JavaScript objects is based on inheritance in the prototype tree—a path to the root in the tree is called a <i>prototype chain</i>—and is separate from name resolution of variables and functions.
</p>
<div class="mw-heading mw-heading3"><h3 id="Lisp">Lisp</h3></div>
<p><a href="Lisp_(programming_language)" title="Lisp (programming language)">Lisp</a> dialects have various rules for scope.
</p><p>The original Lisp used dynamic scope; it was <a href="Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a>, inspired by <a href="ALGOL" title="ALGOL">ALGOL</a>, that introduced static (lexical) scope to the Lisp family.
</p><p><a href="Maclisp" title="Maclisp">Maclisp</a> used dynamic scope by default in the interpreter and lexical scope by default in compiled code, though compiled code could access dynamic bindings by use of <code>SPECIAL</code> declarations for particular variables.<sup id="cite_ref-35" class="reference"><a href="#cite_note-35"><span class="cite-bracket">[</span>29<span class="cite-bracket">]</span></a></sup> However, <a href="Maclisp" title="Maclisp">Maclisp</a> treated lexical binding more as an optimization than one would expect in modern languages, and it did not come with the <a href="Closure_(computer_programming)" title="Closure (computer programming)">closure</a> feature one might expect of lexical scope in modern Lisps. A separate operation, <code>*FUNCTION</code>, was available to somewhat clumsily work around some of that issue.<sup id="cite_ref-36" class="reference"><a href="#cite_note-36"><span class="cite-bracket">[</span>30<span class="cite-bracket">]</span></a></sup>
</p><p><a href="Common_Lisp" title="Common Lisp">Common Lisp</a> adopted lexical scope from <a href="Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a>,<sup id="cite_ref-37" class="reference"><a href="#cite_note-37"><span class="cite-bracket">[</span>31<span class="cite-bracket">]</span></a></sup> as did <a href="Clojure" title="Clojure">Clojure</a>.
</p><p><a href="ISLISP" title="ISLISP">ISLISP</a> has lexical scope for ordinary variables. It also has dynamic variables, but they are in all cases explicitly marked; they must be defined by a <code>defdynamic</code> special form, bound by a <code>dynamic-let</code> special form, and accessed by an explicit <code>dynamic</code> special form.<sup id="cite_ref-38" class="reference"><a href="#cite_note-38"><span class="cite-bracket">[</span>32<span class="cite-bracket">]</span></a></sup>
</p><p>Some other dialects of Lisp, like <a href="Emacs_Lisp" title="Emacs Lisp">Emacs Lisp</a>, still use dynamic scope by default. Emacs Lisp now has lexical scope available on a per-buffer basis.<sup id="cite_ref-:0_39-0" class="reference"><a href="#cite_note-:0-39"><span class="cite-bracket">[</span>33<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading3"><h3 id="Python">Python</h3></div>
<p>For variables, Python has function scope, module scope, and global scope. Names enter context at the start of a scope (function, module, or global scope), and exit context when a non-nested function is called or the scope ends. If a name is used prior to variable initialization, this raises a runtime exception. If a variable is simply accessed (not assigned to), name resolution follows the LEGB (Local, Enclosing, Global, Built-in) rule which resolves names to the narrowest relevant context. However, if a variable is assigned to, it defaults to declaring a variable whose scope starts at the start of the level (function, module, or global), not at the assignment. Both these rules can be overridden with a <code>global</code> or <code>nonlocal</code> (in Python 3) declaration prior to use, which allows accessing global variables even if there is a masking nonlocal variable, and assigning to global or nonlocal variables.
</p><p>As a simple example, a function resolves a variable to the global scope:
</p>
<div class="mw-highlight mw-highlight-lang-pycon mw-content-ltr" dir="ltr"><pre><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="s2">"global"</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
<span class="go">global</span>
</pre></div>
<p>Note that <code>x</code> is defined before <code>f</code> is called, so no error is raised, even though it is defined after its reference in the definition of <code>f</code>. Lexically this is a <a href="Forward_reference" class="mw-redirect" title="Forward reference">forward reference</a>, which is allowed in Python.
</p><p>Here assignment creates a new local variable, which does not change the value of the global variable:
</p>
<div class="mw-highlight mw-highlight-lang-pycon mw-content-ltr" dir="ltr"><pre><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="s2">"f"</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="s2">"global"</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="go">global</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
<span class="go">f</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="go">global</span>
</pre></div>
<p>Assignment to a variable within a function causes it to be declared local to the function, hence its scope is the entire function, and thus using it prior to this assignment raises an error. This differs from C, where the scope of the local variable start at its declaration. This code raises an error:
</p>
<div class="mw-highlight mw-highlight-lang-pycon mw-content-ltr" dir="ltr"><pre><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="s2">"f"</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="s2">"global"</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n">f</span>
<span class="gr">UnboundLocalError</span>: <span class="n">local variable 'x' referenced before assignment</span>
</pre></div>
<p>The default name resolution rules can be overridden with the <code>global</code> or <code>nonlocal</code> (in Python 3) keywords. In the below code, the <code>global x</code> declaration in <code>g</code> means that <code>x</code> resolves to the global variable. It thus can be accessed (as it has already been defined), and assignment assigns to the global variable, rather than declaring a new local variable. Note that no <code>global</code> declaration is needed in <code>f</code>—since it does not assign to the variable, it defaults to resolving to the global variable.
</p>
<div class="mw-highlight mw-highlight-lang-pycon mw-content-ltr" dir="ltr"><pre><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">g</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">global</span> <span class="n">x</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="s2">"g"</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="s2">"global"</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
<span class="go">global</span>
<span class="gp">>>> </span><span class="n">g</span><span class="p">()</span>
<span class="go">global</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
<span class="go">g</span>
</pre></div>
<p><code>global</code> can also be used for nested functions. In addition to allowing assignment to a global variable, as in an unnested function, this can also be used to access the global variable in the presence of a nonlocal variable:
</p>
<div class="mw-highlight mw-highlight-lang-pycon mw-content-ltr" dir="ltr"><pre><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">def</span><span class="w"> </span><span class="nf">g</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">global</span> <span class="n">x</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="s2">"f"</span>
<span class="gp">... </span> <span class="n">g</span><span class="p">()</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="s2">"global"</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
<span class="go">global</span>
</pre></div>
<p>For nested functions, there is also the <code>nonlocal</code> declaration, for assigning to a nonlocal variable, similar to using <code>global</code> in an unnested function:
</p>
<div class="mw-highlight mw-highlight-lang-pycon mw-content-ltr" dir="ltr"><pre><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">def</span><span class="w"> </span><span class="nf">g</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">nonlocal</span> <span class="n">x</span> <span class="c1"># Python 3 only</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="s2">"g"</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="s2">"f"</span>
<span class="gp">... </span> <span class="n">g</span><span class="p">()</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="s2">"global"</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
<span class="go">g</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="go">global</span>
</pre></div>
<div class="mw-heading mw-heading3"><h3 id="R">R</h3></div>
<p><a href="R_(programming_language)" title="R (programming language)">R</a> is a lexically scoped language, unlike other implementations of <a href="S_(programming_language)" title="S (programming language)">S</a> where the values of free variables are determined by a set of global variables, while in R they are determined by the context in which the function was created.<sup id="cite_ref-40" class="reference"><a href="#cite_note-40"><span class="cite-bracket">[</span>34<span class="cite-bracket">]</span></a></sup> The scope contexts may be accessed using a variety of features (such as <code>parent.frame()</code>) which can simulate the experience of dynamic scope should the programmer desire.
</p><p>There is no block scope:
</p>
<div class="mw-highlight mw-highlight-lang-r mw-content-ltr" dir="ltr"><pre><span class="n">a</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="m">1</span>
<span class="p">{</span>
<span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="m">2</span>
<span class="p">}</span>
<span class="nf">message</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="c1">## 2</span>
</pre></div>
<p>Functions have access to scope they were created in:
</p>
<div class="mw-highlight mw-highlight-lang-r mw-content-ltr" dir="ltr"><pre><span class="n">a</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="m">1</span>
<span class="n">f</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="kr">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nf">message</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="p">}</span>
<span class="nf">f</span><span class="p">()</span>
<span class="c1">## 1</span>
</pre></div>
<p>Variables created or modified within a function stay there:
</p>
<div class="mw-highlight mw-highlight-lang-r mw-content-ltr" dir="ltr"><pre><span class="n">a</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="m">1</span>
<span class="n">f</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="nf">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nf">message</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="m">2</span>
<span class="w"> </span><span class="nf">message</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="p">}</span>
<span class="nf">f</span><span class="p">()</span>
<span class="c1">## 1</span>
<span class="c1">## 2</span>
<span class="nf">message</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="c1">## 1</span>
</pre></div>
<p>Variables created or modified within a function stay there unless assignment to enclosing scope is explicitly requested:
</p>
<div class="mw-highlight mw-highlight-lang-r mw-content-ltr" dir="ltr"><pre><span class="n">a</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="m">1</span>
<span class="n">f</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="nf">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nf">message</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o"><<-</span><span class="w"> </span><span class="m">2</span>
<span class="w"> </span><span class="nf">message</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="p">}</span>
<span class="nf">f</span><span class="p">()</span>
<span class="c1">## 1</span>
<span class="c1">## 2</span>
<span class="nf">message</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="c1">## 2</span>
</pre></div>
<p>Although R has lexical scope by default, function scopes can be changed:
</p>
<div class="mw-highlight mw-highlight-lang-r mw-content-ltr" dir="ltr"><pre><span class="n">a</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="m">1</span>
<span class="n">f</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="kr">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nf">message</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="p">}</span>
<span class="n">my_env</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="nf">new.env</span><span class="p">()</span>
<span class="n">my_env</span><span class="o">$</span><span class="n">a</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="m">2</span>
<span class="nf">f</span><span class="p">()</span>
<span class="c1">## 1</span>
<span class="nf">environment</span><span class="p">(</span><span class="n">f</span><span class="p">)</span><span class="w"> </span><span class="o"><-</span><span class="w"> </span><span class="n">my_env</span>
<span class="nf">f</span><span class="p">()</span>
<span class="c1">## 2</span>
</pre></div>
<div class="mw-heading mw-heading2"><h2 id="Notes">Notes</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1239543626">
/* start https://en.wikipedia.org/ */
.mw-parser-output .reflist{margin-bottom:0.5em;list-style-type:decimal}@media screen{.mw-parser-output .reflist{font-size:90%}}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}
/* end https://en.wikipedia.org/ */
</style><div class="reflist reflist-lower-alpha">
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text">See <a href="#Definition">definition</a> for meaning of "scope" versus "context".</span>
</li>
<li id="cite_note-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-2">^</a></b></span> <span class="reference-text">"Dynamic scope" bases name resolution on <i>extent</i> (lifetime), not <i>scope</i>, and thus is formally inaccurate.</span>
</li>
<li id="cite_note-7"><span class="mw-cite-backlink"><b><a href="#cite_ref-7">^</a></b></span> <span class="reference-text">For example, the <a href="Jinja_(template_engine)" title="Jinja (template engine)">Jinja</a> template engine for Python by default uses both lexical scope (for imports) and dynamic scope (for includes), and allows behavior to be specified with keywords; see <a rel="nofollow" class="external text" href="http://jinja.pocoo.org/docs/templates/#import-context-behavior">Import Context Behavior</a>.</span>
</li>
<li id="cite_note-9"><span class="mw-cite-backlink"><b><a href="#cite_ref-9">^</a></b></span> <span class="reference-text">"Name resolution" and "name binding" are largely synonymous; narrowly speaking "resolution" determines to which name a particular use of a name refers, without associating it with any meaning, as in <a href="Higher-order_abstract_syntax" title="Higher-order abstract syntax">higher-order abstract syntax</a>, while "binding" associates the name with an actual meaning. In practice the terms are used interchangeably.</span>
</li>
<li id="cite_note-10"><span class="mw-cite-backlink"><b><a href="#cite_ref-10">^</a></b></span> <span class="reference-text">For <a href="Self-modifying_code" title="Self-modifying code">self-modifying code</a> the lexical context itself can change during run time.</span>
</li>
<li id="cite_note-11"><span class="mw-cite-backlink"><b><a href="#cite_ref-11">^</a></b></span> <span class="reference-text">By contrast, *"a name binding's context", *"a name binding coming into scope" or *"a name binding going out of scope" are all incorrect—a name binding has scope, while a part of a program has context.</span>
</li>
</ol></div></div>
<div class="mw-heading mw-heading2"><h2 id="References">References</h2></div>
<div class="reflist">
<div class="mw-references-wrap mw-references-columns"><ol class="references">
<li id="cite_note-RALA60_2.7-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-RALA60_2.7_3-0">^</a></b></span> <span class="reference-text">"Report on the Algorithmic Language Algol 60", 2.7. Quantities, kinds and scopes</span>
</li>
<li id="cite_note-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-4">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf">WG14 N1256</a> (2007 updated version of the <a href="C99" title="C99">C99</a> standard), 6.2.1 Scopes of identifiers, 2007-09-07</span>
</li>
<li id="cite_note-go-5"><span class="mw-cite-backlink">^ <a href="#cite_ref-go_5-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-go_5-1"><sup><i><b>b</b></i></sup></a></span> <span class="reference-text"><a rel="nofollow" class="external text" href="https://golang.org/ref/spec">The Go Programming Language Specification</a>: <a rel="nofollow" class="external text" href="https://golang.org/ref/spec#Declarations_and_scope">Declarations and scope</a>, Version of Nov 13, 2013</span>
</li>
<li id="cite_note-Borning-6"><span class="mw-cite-backlink">^ <a href="#cite_ref-Borning_6-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-Borning_6-1"><sup><i><b>b</b></i></sup></a> <a href="#cite_ref-Borning_6-2"><sup><i><b>c</b></i></sup></a></span> <span class="reference-text">Borning A. <a rel="nofollow" class="external text" href="https://web.archive.org/web/20150207225438/http://courses.cs.washington.edu/courses/cse341/08au/general-concepts/scoping.html">CSE 341 -- Lexical and Dynamic Scoping</a>. University of Washington.</span>
</li>
<li id="cite_note-js-conventions-8"><span class="mw-cite-backlink"><b><a href="#cite_ref-js-conventions_8-0">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1238218222">
/* start https://en.wikipedia.org/ */
.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("./mw/Lock-green.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("./mw/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("./mw/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-ws-icon a{background:url("./mw/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain;padding:0 1em 0 0}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:var(--color-error,#d33)}.mw-parser-output .cs1-visible-error{color:var(--color-error,#d33)}.mw-parser-output .cs1-maint{display:none;color:#085;margin-left:0.3em}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}@media screen{.mw-parser-output .cs1-format{font-size:95%}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911f}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911f}}
/* end https://en.wikipedia.org/ */
</style><cite id="CITEREFCrockford" class="citation web cs1">Crockford, Douglas. <a rel="nofollow" class="external text" href="https://docs.angularjs.org/guide/scope">"Code Conventions for the JavaScript Programming Language"</a><span class="reference-accessdate">. Retrieved <span class="nowrap">2015-01-04</span></span>.</cite></span>
</li>
<li id="cite_note-12"><span class="mw-cite-backlink"><b><a href="#cite_ref-12">^</a></b></span> <span class="reference-text"><cite id="CITEREFBackusWegsteinVan_WijngaardenWoodger1960" class="citation journal cs1">Backus, J. W.; Wegstein, J. H.; Van Wijngaarden, A.; Woodger, M.; Bauer, F. L.; Green, J.; Katz, C.; McCarthy, J.; Perlis, A. J.; Rutishauser, H.; Samelson, K.; Vauquois, B. (1960). <a rel="nofollow" class="external text" href="https://doi.org/10.1145%2F367236.367262">"Report on the algorithmic language ALGOL 60"</a>. <i>Communications of the ACM</i>. <b>3</b> (5): 299. <a href="Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<span class="id-lock-free" title="Freely accessible"><a rel="nofollow" class="external text" href="https://doi.org/10.1145%2F367236.367262">10.1145/367236.367262</a></span>. <a href="S2CID_(identifier)" class="mw-redirect" title="S2CID (identifier)">S2CID</a> <a rel="nofollow" class="external text" href="https://api.semanticscholar.org/CorpusID:278290">278290</a>.</cite></span>
</li>
<li id="cite_note-13"><span class="mw-cite-backlink"><b><a href="#cite_ref-13">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#function_scope">"Functions - Javascript:MDN"</a>. 23 April 2023. <q>Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined.</q></cite></span>
</li>
<li id="cite_note-14"><span class="mw-cite-backlink"><b><a href="#cite_ref-14">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://isocpp.org/files/papers/n4720.pdf">"N4720: Working Draft, Extensions to C++ for Modules"</a> <span class="cs1-format">(PDF)</span>. <a rel="nofollow" class="external text" href="https://web.archive.org/web/20190430095053/https://isocpp.org/files/papers/n4720.pdf">Archived</a> <span class="cs1-format">(PDF)</span> from the original on 2019-04-30<span class="reference-accessdate">. Retrieved <span class="nowrap">2019-04-30</span></span>.</cite></span>
</li>
<li id="cite_note-15"><span class="mw-cite-backlink"><b><a href="#cite_ref-15">^</a></b></span> <span class="reference-text">"<a rel="nofollow" class="external text" href="http://booksite.elsevier.com/9780123745149/appendices/data/chapters/3a_impsc.pdf">Programming Language Pragmatics</a>", LeBlank-Cook symbol table</span>
</li>
<li id="cite_note-16"><span class="mw-cite-backlink"><b><a href="#cite_ref-16">^</a></b></span> <span class="reference-text">"<a rel="nofollow" class="external text" href="http://origin-www.computer.org/csdl/trans/ts/1983/01/01703006.pdf">A Symbol Table Abstraction to Implement Languages with Explicit Scope Control</a>", LeBlank-Cook, 1983</span>
</li>
<li id="cite_note-17"><span class="mw-cite-backlink"><b><a href="#cite_ref-17">^</a></b></span> <span class="reference-text"><cite id="CITEREFLouis_Steele1982" class="citation book cs1">Louis Steele, Guy (August 1982). "An overview of COMMON LISP". <i>Proceedings of the 1982 ACM symposium on LISP and functional programming - LFP '82</i>. pp. <span class="nowrap">98–</span>107. <a href="Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<a rel="nofollow" class="external text" href="https://doi.org/10.1145%2F800068.802140">10.1145/800068.802140</a>. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <bdi>0-89791-082-6</bdi>. <a href="S2CID_(identifier)" class="mw-redirect" title="S2CID (identifier)">S2CID</a> <a rel="nofollow" class="external text" href="https://api.semanticscholar.org/CorpusID:14517358">14517358</a>.</cite></span>
</li>
<li id="cite_note-18"><span class="mw-cite-backlink"><b><a href="#cite_ref-18">^</a></b></span> <span class="reference-text"><cite id="CITEREFJoel1970" class="citation journal cs1">Joel, Moses (June 1970). "The Function of FUNCTION in LISP". <i>MIT AI Memo 199</i>. MIT Artificial Intelligence Lab.</cite></span>
</li>
<li id="cite_note-19"><span class="mw-cite-backlink"><b><a href="#cite_ref-19">^</a></b></span> <span class="reference-text"><cite id="CITEREFSteeleSussman1978" class="citation journal cs1">Steele, Guy Lewis Jr.; Sussman, Gerald Jay (May 1978). "The Art of the Interpreter; or, The Modularity Complex (Parts Zero, One and Two)". <i>MIT AI Memo 453</i>. MIT Artificial Intelligence Lab.</cite></span>
</li>
<li id="cite_note-20"><span class="mw-cite-backlink"><b><a href="#cite_ref-20">^</a></b></span> <span class="reference-text"><cite id="CITEREFShivers" class="citation web cs1">Shivers, Olin. <a rel="nofollow" class="external text" href="http://www.paulgraham.com/thist.html">"History of T"</a>. <i>Paul Graham</i><span class="reference-accessdate">. Retrieved <span class="nowrap">5 February</span> 2020</span>.</cite></span>
</li>
<li id="cite_note-21"><span class="mw-cite-backlink"><b><a href="#cite_ref-21">^</a></b></span> <span class="reference-text"><cite id="CITEREFSteele1978" class="citation techreport cs1">Steele, Guy Lewis Jr. (May 1978). <i>RABBIT: A Compiler for SCHEME</i> (Technical report). Massachusetts Institute of Technology. <a href="Hdl_(identifier)" class="mw-redirect" title="Hdl (identifier)">hdl</a>:<span class="id-lock-free" title="Freely accessible"><a rel="nofollow" class="external text" href="https://hdl.handle.net/1721.1%2F6913">1721.1/6913</a></span>.</cite></span>
</li>
<li id="cite_note-22"><span class="mw-cite-backlink"><b><a href="#cite_ref-22">^</a></b></span> <span class="reference-text">"<a rel="nofollow" class="external text" href="https://books.google.com/books?id=qk0jAQAAMAAJ&q=%22lexical+scope%22">lexical scope</a>", <i><a rel="nofollow" class="external text" href="https://books.google.com/books?id=qk0jAQAAMAAJ&pg=PA18">Computer and Program Organization, Part 3</a></i>, p. 18, at <a href="Google_Books" title="Google Books">Google Books</a>, University of Michigan. Engineering Summer Conferences, 1967</span>
</li>
<li id="cite_note-23"><span class="mw-cite-backlink"><b><a href="#cite_ref-23">^</a></b></span> <span class="reference-text">
"<a rel="nofollow" class="external text" href="https://books.google.com/books?id=m0IdAQAAMAAJ&q=%22lexical+scoping%22">lexical scoping</a>", <i><a rel="nofollow" class="external text" href="https://books.google.com/books?id=m0IdAQAAMAAJ&pg=PA80">Project MAC Progress Report, Volume 8</a></i>, p. 80, at <a href="Google_Books" title="Google Books">Google Books</a>, 1970.</span>
</li>
<li id="cite_note-FOOTNOTEScott20093.4_Implementing_Scope,_p._143-24"><span class="mw-cite-backlink">^ <a href="#cite_ref-FOOTNOTEScott20093.4_Implementing_Scope,_p._143_24-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-FOOTNOTEScott20093.4_Implementing_Scope,_p._143_24-1"><sup><i><b>b</b></i></sup></a></span> <span class="reference-text"><a href="#CITEREFScott2009">Scott 2009</a>, 3.4 Implementing Scope, p. 143.</span>
</li>
<li id="cite_note-25"><span class="mw-cite-backlink"><b><a href="#cite_ref-25">^</a></b></span> <span class="reference-text">"<a rel="nofollow" class="external text" href="http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fzexscope_c.htm">Scope</a>", <i>XL C/C++ V8.0 for Linux,</i> IBM</span>
</li>
<li id="cite_note-26"><span class="mw-cite-backlink"><b><a href="#cite_ref-26">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html">"Declaring Member Variables (The Java Tutorials > Learning the Java Language > Classes and Objects)"</a>. <i>docs.oracle.com</i><span class="reference-accessdate">. Retrieved <span class="nowrap">19 March</span> 2018</span>.</cite></span>
</li>
<li id="cite_note-27"><span class="mw-cite-backlink"><b><a href="#cite_ref-27">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html">"Controlling Access to Members of a Class (The Java Tutorials > Learning the Java Language > Classes and Objects)"</a>. <i>docs.oracle.com</i><span class="reference-accessdate">. Retrieved <span class="nowrap">19 March</span> 2018</span>.</cite></span>
</li>
<li id="cite_note-28"><span class="mw-cite-backlink"><b><a href="#cite_ref-28">^</a></b></span> <span class="reference-text">"<a rel="nofollow" class="external text" href="http://www.coolcoder.in/2014/03/everything-you-need-to-know-about.html">Everything you need to know about Javascript variable scope</a>", <a rel="nofollow" class="external text" href="http://www.coolcoder.in/p/about-us.html">Saurab Parakh</a>, <i><a rel="nofollow" class="external text" href="http://www.coolcoder.in/">Coding is Cool</a>,</i> 2010-02-08</span>
</li>
<li id="cite_note-29"><span class="mw-cite-backlink"><b><a href="#cite_ref-29">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://es5.github.io/#x10.2">"Annotated ES5"</a>. <i>es5.github.io</i><span class="reference-accessdate">. Retrieved <span class="nowrap">19 March</span> 2018</span>.</cite></span>
</li>
<li id="cite_note-30"><span class="mw-cite-backlink"><b><a href="#cite_ref-30">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope">"Functions"</a>. <i>MDN Web Docs</i><span class="reference-accessdate">. Retrieved <span class="nowrap">19 March</span> 2018</span>.</cite></span>
</li>
<li id="cite_note-31"><span class="mw-cite-backlink"><b><a href="#cite_ref-31">^</a></b></span> <span class="reference-text">"<a rel="nofollow" class="external text" href="https://es5.github.io/#x12.2">12.2 Variable Statement</a>", Annotated ECMAScript 5.1, Last updated: 2012-05-28</span>
</li>
<li id="cite_note-32"><span class="mw-cite-backlink"><b><a href="#cite_ref-32">^</a></b></span> <span class="reference-text">"<a rel="nofollow" class="external text" href="http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html">JavaScript Scoping and Hoisting</a>", <a rel="nofollow" class="external text" href="http://www.adequatelygood.com/about.html">Ben Cherry</a>, <i><a rel="nofollow" class="external text" href="http://www.adequatelygood.com/">Adequately Good</a>,</i> 2010-02-08</span>
</li>
<li id="cite_note-33"><span class="mw-cite-backlink"><b><a href="#cite_ref-33">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://jibbering.com/faq/notes/closures/">Javascript Closures</a>, Richard Cornford. March 2004</span>
</li>
<li id="cite_note-34"><span class="mw-cite-backlink"><b><a href="#cite_ref-34">^</a></b></span> <span class="reference-text">
"<a rel="nofollow" class="external text" href="http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/">Explaining JavaScript Scope And Closures</a>", Robert Nyman, October 9, 2008</span>
</li>
<li id="cite_note-35"><span class="mw-cite-backlink"><b><a href="#cite_ref-35">^</a></b></span> <span class="reference-text"><cite id="CITEREFPitman2007" class="citation web cs1">Pitman, Kent (December 16, 2007). <a rel="nofollow" class="external text" href="http://maclisp.info/pitmanual/complr.html#23.1.2">"The Revised Maclisp Manual (The Pitmanual), Sunday Morning Edition"</a>. <i>MACLISP.info</i>. HyperMeta Inc. Declarations and the Compiler, Concept "Variables"<span class="reference-accessdate">. Retrieved <span class="nowrap">October 20,</span> 2018</span>. <q>If the variable to be bound has been declared to be special, the binding is compiled as code to imitate the way the interpreter binds variables</q></cite></span>
</li>
<li id="cite_note-36"><span class="mw-cite-backlink"><b><a href="#cite_ref-36">^</a></b></span> <span class="reference-text"><cite id="CITEREFPitman2007" class="citation web cs1">Pitman, Kent (December 16, 2007). <a rel="nofollow" class="external text" href="http://www.maclisp.info/pitmanual/eval.html#3.7.1">"The Revised Maclisp Manual (The Pitmanual), Sunday Morning Edition"</a>. <i>MACLISP.info</i>. HyperMeta Inc. The Evaluator, Special Form <code>*FUNCTION</code><span class="reference-accessdate">. Retrieved <span class="nowrap">October 20,</span> 2018</span>. <q><code>*FUNCTION</code> is intended to help solve the "<a href="Funarg_problem" title="Funarg problem">funarg problem</a>," however it only works in some easy cases.</q></cite></span>
</li>
<li id="cite_note-37"><span class="mw-cite-backlink"><b><a href="#cite_ref-37">^</a></b></span> <span class="reference-text"><cite id="CITEREFPitman1996" class="citation web cs1">Pitman, Kent; et al. (webbed version of ANSI standard X3.226-1994) (1996). <a rel="nofollow" class="external text" href="http://www.lispworks.com/documentation/lw50/CLHS/Body/01_ab.htm">"Common Lisp HyperSpec"</a>. <i>Lispworks.com</i>. LispWorks Ltd. 1.1.2 History<span class="reference-accessdate">. Retrieved <span class="nowrap">October 20,</span> 2018</span>. <q>MacLisp improved on the Lisp 1.5 notion of special variables ... The primary influences on Common Lisp were Lisp Machine Lisp, MacLisp, NIL, S-1 Lisp, Spice Lisp, and Scheme.</q></cite></span>
</li>
<li id="cite_note-38"><span class="mw-cite-backlink"><b><a href="#cite_ref-38">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://www.islisp.info/Documents/PDF/islisp-2007-03-17-pd-v23.pdf">"Programming Language ISLISP, ISLISP Working Draft 23.0"</a> <span class="cs1-format">(PDF)</span>. <i>ISLISP.info</i>. 11.1 The lexical principle<span class="reference-accessdate">. Retrieved <span class="nowrap">October 20,</span> 2018</span>. <q>Dynamic bindings are established and accessed by a separate mechanism (i.e., <code>defdynamic</code>, <code>dynamic-let</code>, and <code>dynamic</code>).</q></cite></span>
</li>
<li id="cite_note-:0-39"><span class="mw-cite-backlink"><b><a href="#cite_ref-:0_39-0">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://www.emacswiki.org/emacs/LexicalBinding">"Lexical Binding"</a>. <i>EmacsWiki</i><span class="reference-accessdate">. Retrieved <span class="nowrap">October 20,</span> 2018</span>. <q>Emacs 24 has optional lexical binding, which can be enabled on a per-buffer basis.</q></cite></span>
</li>
<li id="cite_note-40"><span class="mw-cite-backlink"><b><a href="#cite_ref-40">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://cran.r-project.org/doc/FAQ/R-FAQ.html#Lexical-scoping">"R FAQ"</a>. <i>cran.r-project.org</i><span class="reference-accessdate">. Retrieved <span class="nowrap">19 March</span> 2018</span>.</cite></span>
</li>
</ol></div></div>
<style data-mw-deduplicate="TemplateStyles:r1239549316">
/* start https://en.wikipedia.org/ */
.mw-parser-output .refbegin{margin-bottom:0.5em}.mw-parser-output .refbegin-hanging-indents>ul{margin-left:0}.mw-parser-output .refbegin-hanging-indents>ul>li{margin-left:0;padding-left:3.2em;text-indent:-3.2em}.mw-parser-output .refbegin-hanging-indents ul,.mw-parser-output .refbegin-hanging-indents ul li{list-style:none}@media(max-width:720px){.mw-parser-output .refbegin-hanging-indents>ul>li{padding-left:1.6em;text-indent:-1.6em}}.mw-parser-output .refbegin-columns{margin-top:0.3em}.mw-parser-output .refbegin-columns ul{margin-top:0}.mw-parser-output .refbegin-columns li{page-break-inside:avoid;break-inside:avoid-column}@media screen{.mw-parser-output .refbegin{font-size:90%}}
/* end https://en.wikipedia.org/ */
</style><div class="refbegin" style="">
<ul><li><cite id="CITEREFAbelsonSussmanSussman1996" class="citation book cs1"><a href="Harold_Abelson" class="mw-redirect" title="Harold Abelson">Abelson, Harold</a>; <a href="Gerald_Jay_Sussman" title="Gerald Jay Sussman">Sussman, Gerald Jay</a>; Sussman, Julie (1996) [1984]. <a href="Structure_and_Interpretation_of_Computer_Programs" title="Structure and Interpretation of Computer Programs"><i>Structure and Interpretation of Computer Programs</i></a>. Cambridge, MA: <a href="MIT_Press" title="MIT Press">MIT Press</a>. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <bdi>0-262-51087-1</bdi>.</cite>
<ul><li><a rel="nofollow" class="external text" href="https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-35.html#%_sec_5.5.6">"Lexical addressing"</a></li></ul></li>
<li><cite id="CITEREFScott2009" class="citation book cs1"><a href="Michael_L._Scott" title="Michael L. Scott">Scott, Michael L.</a> (2009) [2000]. <a rel="nofollow" class="external text" href="https://www.cs.rochester.edu/~scott/pragmatics/"><i>Programming Language Pragmatics</i></a> (Third ed.). Morgan Kaufmann Publishers. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <bdi>978-0-12-374514-9</bdi>.</cite>
<ul><li>Chapter 3: Names, Scopes, and Bindings, pp. 111–174</li>
<li>Section 13.4.1: Scripting Languages: Innovative Features: Names and Scopes, pp. 691–699</li></ul></li></ul>
</div></div><!--htdig_noindex--><div><div class="zim-footer">
This article is issued from <a class="external text" title="Last edited on 2025-07-30" href="https://en.wikipedia.org/wiki/?title=Scope_(computer_science)&oldid=1303386321">Wikipedia</a>. The text is available under <a class="external text" href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons Attribution-Share Alike 4.0</a> unless otherwise noted. Additional terms may apply for the media files.
</div>
</div><!--/htdig_noindex--></div>
</div>
</main>
</div>
</div>
</div>
</body></html>